# ADDITIVE: real-time eSSL -> HRMS sync worker.
#   python manage.py essl_sync --once                     one pass over every enabled source (cron: * * * * *)
#   python manage.py essl_sync --loop --interval 10 --max-seconds 55    poll every 10 s for 55 s (1-minute cron = near real time)
#   python manage.py essl_sync --source-id 3 --drain      catch up a big backlog of one source
import time

from django.core.management.base import BaseCommand

from People.att_models import EsslSource
from People.essl_sync import sync_source, sync_until_empty


class Command(BaseCommand):
    help = "Sync new punches from the eSSL MySQL database into the HRMS attendance records."

    def add_arguments(self, p):
        p.add_argument("--company-id")
        p.add_argument("--source-id", type=int)
        p.add_argument("--once", action="store_true", help="run one pass and exit (default)")
        p.add_argument("--loop", action="store_true", help="keep polling")
        p.add_argument("--interval", type=int, default=10, help="seconds between polls with --loop")
        p.add_argument("--max-seconds", type=int, default=0, help="stop looping after N seconds (0 = forever)")
        p.add_argument("--drain", action="store_true", help="repeat passes until the backlog is empty")

    def sources(self, o):
        qs = EsslSource.objects.filter(is_active=True, enabled=True)
        if o.get("company_id"):
            qs = qs.filter(company__company_id=o["company_id"])
        if o.get("source_id"):
            qs = qs.filter(pk=o["source_id"])
        return list(qs)

    def one_pass(self, o):
        for s in self.sources(o):
            if o.get("drain"):
                run, total = sync_until_empty(s, trigger="command")
            else:
                run = sync_source(s, trigger="command")
            self.stdout.write(f"[{s.name}] {run.status}: fetched={run.rows_fetched} reconciled={run.reconciled} "
                              f"unmatched={run.unmatched} duplicates={run.duplicates} failed={run.failed}"
                              + (f" error={run.error}" if run.error else ""))

    def handle(self, *a, **o):
        if not o["loop"]:
            return self.one_pass(o)
        start = time.time()
        while True:
            self.one_pass(o)
            if o["max_seconds"] and time.time() - start + o["interval"] > o["max_seconds"]:
                break
            time.sleep(o["interval"])
