"""
Point d'entrée du crawler. Lance le scheduler et exécute les jobs périodiques.

Jobs :
  - Toutes les SCHED_INCREMENTAL_H heures : crawl incrémental (additions + modifications)
  - Toutes les SCHED_ENRICH_H heures      : enrichissement des bands non enrichies
  - Le SCHED_FULL_DAY du mois             : crawl complet Europe

Variables d'env :
  DATABASE_URL            (obligatoire)
  FLARESOLVERR_URL        (défaut: http://flaresolverr:8191)
  CRAWLER_SCHED_INCREMENTAL_H  (défaut: 4)
  CRAWLER_SCHED_ENRICH_H       (défaut: 1)
  CRAWLER_SCHED_FULL_DAY       (défaut: 1, mettre 0 pour désactiver)
"""
import logging
import os
import sys
import time
from datetime import datetime, timezone

import schedule

from .config import (
    FLARESOLVERR_URL, FS_TIMEOUT_MS,
    SCHED_INCREMENTAL_H, SCHED_ENRICH_H, SCHED_FULL_DAY,
    ENRICH_LIMIT,
)
from .flaresolverr import FlareSolverr, FlareSolverrError
from .db import claim_job_trigger, finish_job_trigger
from .jobs import run_full_crawl, run_incremental, run_enrich
from .ma_http import MASession

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    datefmt="%Y-%m-%dT%H:%M:%S",
    stream=sys.stdout,
)
log = logging.getLogger(__name__)


def _wait_flaresolverr(fs: FlareSolverr, max_wait: int = 120):
    log.info("[main] waiting for FlareSolverr...")
    for _ in range(max_wait // 5):
        if fs.healthy():
            log.info("[main] FlareSolverr is up")
            return
        time.sleep(5)
    raise RuntimeError("FlareSolverr not reachable after timeout")


def main():
    log.info("[main] crawler starting")
    fs = FlareSolverr(FLARESOLVERR_URL, timeout_ms=FS_TIMEOUT_MS)
    _wait_flaresolverr(fs)

    ma = MASession(fs)

    # ------------------------------------------------------------------
    # Helpers pour lancer les jobs avec log
    # ------------------------------------------------------------------

    def job_incremental():
        log.info("[scheduler] → incremental additions")
        run_incremental(ma, "created")
        log.info("[scheduler] → incremental modifications")
        run_incremental(ma, "modified")

    def job_enrich():
        log.info("[scheduler] → enrich")
        run_enrich(ma, limit=ENRICH_LIMIT)

    def job_full():
        if SCHED_FULL_DAY and datetime.now(timezone.utc).day == SCHED_FULL_DAY:
            log.info("[scheduler] → full Europe crawl")
            run_full_crawl(ma)

    # ------------------------------------------------------------------
    # Planification
    # ------------------------------------------------------------------

    if SCHED_INCREMENTAL_H > 0:
        schedule.every(SCHED_INCREMENTAL_H).hours.do(job_incremental)
        log.info(f"[main] incremental scheduled every {SCHED_INCREMENTAL_H}h")

    if SCHED_ENRICH_H > 0:
        schedule.every(SCHED_ENRICH_H).hours.do(job_enrich)
        log.info(f"[main] enrich scheduled every {SCHED_ENRICH_H}h")

    if SCHED_FULL_DAY > 0:
        # Vérifier chaque jour à 03:00 UTC si c'est le bon jour
        schedule.every().day.at("03:00").do(job_full)
        log.info(f"[main] full crawl scheduled day={SCHED_FULL_DAY} of each month at 03:00 UTC")

    # Premier run au démarrage
    log.info("[main] running initial jobs at startup")
    job_incremental()
    job_enrich()

    log.info("[main] entering scheduler loop")
    while True:
        schedule.run_pending()
        _check_job_triggers(ma)
        time.sleep(60)


def _check_job_triggers(ma: "MASession"):
    """Consomme les job_triggers en attente créés depuis l'admin."""
    result = claim_job_trigger()
    if not result:
        return
    trigger_id, job_type = result
    log.info(f"[main] job trigger #{trigger_id}: {job_type}")
    error = None
    try:
        if job_type == "enrich":
            run_enrich(ma, limit=ENRICH_LIMIT)
        elif job_type == "incremental":
            run_incremental(ma, "created")
            run_incremental(ma, "modified")
        elif job_type == "full_crawl":
            run_full_crawl(ma)
        else:
            error = f"job_type inconnu: {job_type}"
            log.warning(f"[main] {error}")
    except Exception as e:
        error = str(e)
        log.error(f"[main] job trigger #{trigger_id} error: {e}", exc_info=True)
    finally:
        finish_job_trigger(trigger_id, error)


if __name__ == "__main__":
    main()
