"""
Dispatcher degli agenti live: trova le partite nella finestra giusta e lancia
l'agente formazioni per ciascuna (una sola volta per stage).

  S1: partite di Serie A con calcio d'inizio tra 20 e 30 ore da adesso
  S2: partite di Serie A con calcio d'inizio tra 40 e 80 minuti da adesso

Pensato per lo scheduler: esce subito se non c'è nulla da fare.

Uso:
    python scripts/run_agents.py --stage S1
    python scripts/run_agents.py --stage S2
"""

import argparse
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path

import pymysql

import config

SCRIPTS = Path(__file__).resolve().parent
MVP_LEAGUES = ["I1"]          # perimetro MVP dal design: solo Serie A

WINDOWS = {
    "S1": (timedelta(hours=20), timedelta(hours=30)),
    "S2": (timedelta(minutes=40), timedelta(minutes=80)),
}


def main() -> int:
    parser = argparse.ArgumentParser(description="Dispatcher agenti live")
    parser.add_argument("--stage", choices=["S1", "S2"], required=True)
    config.add_db_args(parser)
    args = parser.parse_args()

    lo, hi = WINDOWS[args.stage]
    now = datetime.now()

    conn = pymysql.connect(host=args.host, port=args.port, user=args.user,
                           password=args.password, database="tigertips")
    cur = conn.cursor()
    cur.execute(f"""
        SELECT m.id, l.code, h.name, a.name, m.match_date, m.match_time
        FROM matches m
        JOIN leagues l ON l.id = m.league_id
        JOIN teams h ON h.id = m.home_team_id
        JOIN teams a ON a.id = m.away_team_id
        WHERE m.result IS NULL
          AND l.code IN ({','.join(['%s'] * len(MVP_LEAGUES))})
          AND m.match_date BETWEEN %s AND %s
          AND NOT EXISTS (SELECT 1 FROM agent_signals s
                          WHERE s.match_id = m.id AND s.stage = %s)
    """, MVP_LEAGUES + [now.date(), (now + hi).date(), args.stage])
    rows = cur.fetchall()
    conn.close()

    todo = []
    for mid, league, home, away, mdate, mtime in rows:
        if mtime is None:
            if args.stage == "S2":
                continue          # senza orario non possiamo centrare la finestra
            kickoff = datetime.combine(mdate, datetime.min.time()) + timedelta(hours=18)
        else:
            kickoff = datetime.combine(mdate, datetime.min.time()) + mtime
        if lo <= kickoff - now <= hi:
            todo.append((league, home, away, kickoff))

    if not todo:
        return 0
    print(f"[{now:%Y-%m-%d %H:%M}] {args.stage}: {len(todo)} partite in finestra")
    for league, home, away, kickoff in todo:
        print(f"  -> {home} - {away} ({kickoff:%d/%m %H:%M})")
        subprocess.run([sys.executable, str(SCRIPTS / "agent_formazioni.py"),
                        "--league", league, "--home", home, "--away", away,
                        "--kickoff", kickoff.strftime("%Y-%m-%d %H:%M"),
                        "--stage", args.stage],
                       timeout=900)
    return 0


if __name__ == "__main__":
    sys.exit(main())
