#!/bin/bash
# vh_relevance.sh — SQL-аудит relevance: соответствуют ли источники
# выданных вакансий заявленному типу занятости в подписке?
#
# Запускать на mac mini.

set -u
DB="/Users/cebers_mini/Services/VakHunter/vakhunter.db"

echo "=== Relevance audit ==="

echo ""
echo "--- subscriptions.employment_type распределение ---"
sqlite3 -column -header "$DB" "SELECT COALESCE(NULLIF(employment_type,''),'(empty)') AS et, COUNT(*) AS n FROM subscriptions WHERE is_active=1 GROUP BY et;"

echo ""
echo "--- если employment_type='permanent', а в выданных вакансиях есть фриланс-источники → mismatch ---"
sqlite3 -column -header "$DB" "
SELECT s.user_id, s.employment_type, v.source, COUNT(*) AS n_sent
FROM sent_vacancies sv
JOIN subscriptions s ON s.user_id=sv.user_id AND s.is_active=1
JOIN vacancies v ON v.id=sv.vacancy_id
WHERE s.employment_type='permanent'
  AND v.source IN ('fl.ru','kwork.ru','profi.ru','avito-services')
  AND sv.sent_at >= datetime('now','-30 day')
GROUP BY s.user_id, s.employment_type, v.source
ORDER BY n_sent DESC
LIMIT 20;
"

echo ""
echo "--- avito_services_parser баг: проверяем что записывает в employment_type ---"
sqlite3 -column -header "$DB" "
SELECT source, employment_type, COUNT(*) AS n
FROM vacancies
WHERE source='avito-services'
GROUP BY source, employment_type;
"

echo ""
echo "--- vacancies без явного employment_type (мягкое прохождение фильтра) ---"
sqlite3 -column -header "$DB" "
SELECT source, COUNT(*) AS n_any
FROM vacancies
WHERE (employment_type IS NULL OR employment_type='' OR employment_type='any')
  AND created_at >= datetime('now','-7 day')
GROUP BY source
ORDER BY n_any DESC;
"

echo ""
echo "=== relevance audit complete ==="
