"""Watch the inbox folder and auto-ingest JSON files.

Standards: Enterprise Integration Patterns File Consumer;
process-once via file-move; audit trail via processed/failed folders.

Usage: python manage.py watch_reports [--with-pdf]
"""
import shutil
from datetime import datetime, timezone
from pathlib import Path

from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Ingest JSON files in inbox, move to processed/ on success."

    def add_arguments(self, parser):
        parser.add_argument("--with-pdf", action="store_true")

    def handle(self, *args, **options):
        base = Path(settings.BASE_DIR).parent
        inbox = base / "inbox"
        processed = base / "processed"
        failed = base / "failed"
        for d in (inbox, processed, failed):
            d.mkdir(parents=True, exist_ok=True)
        files = sorted(inbox.glob("*.json"))
        if not files:
            self.stdout.write("Inbox empty.")
            return
        today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
        proc_day = processed / today
        proc_day.mkdir(parents=True, exist_ok=True)
        ok = 0
        bad = 0
        for f in files:
            self.stdout.write("Processing: " + f.name)
            try:
                call_command("ingest_reports", str(f), pdf=options["with_pdf"])
                shutil.move(str(f), str(proc_day / f.name))
                ok += 1
            except Exception as e:
                self.stderr.write("FAILED " + f.name + ": " + str(e))
                _append_failed_alert(f, e, failed)
                shutil.move(str(f), str(failed / f.name))
                bad += 1
        self.stdout.write(self.style.SUCCESS("Done. ok=" + str(ok) + " failed=" + str(bad)))


def _append_failed_alert(f, exc, failed_dir):
    from datetime import datetime, timezone
    import json
    log_path = failed_dir.parent / "tmp" / "failed_alerts.jsonl"
    log_path.parent.mkdir(parents=True, exist_ok=True)
    entry = {
        "ts": datetime.now(timezone.utc).isoformat(),
        "file": str(f),
        "error": str(exc),
    }
    with log_path.open("a", encoding="utf-8") as fh:
        fh.write(json.dumps(entry) + chr(10))
