"""Single entry point for cron. Respects SystemState, then dispatches work."""
from pathlib import Path

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

from exams.models import SystemState


class Command(BaseCommand):
    help = "One-shot cron tick. Skips work when dormant or in maintenance."

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

    def handle(self, *args, **opts):
        _rotate_cron_log(Path(settings.BASE_DIR).parent)
        st = SystemState.get()
        base = Path(settings.BASE_DIR).parent
        inbox = base / "inbox"
        inbox.mkdir(parents=True, exist_ok=True)
        pending = sorted(inbox.glob("*.json"))
        state = st.state
        if state == "MAINT":
            self.stdout.write("MAINT - skipping all work.")
            return
        if state == "DORMANT" and not pending:
            self.stdout.write("DORMANT and inbox empty - skipping.")
            return
        if state == "DORMANT" and pending:
            st.state = "ACTIVE"
            st.dormant_since = None
            st.note = "auto: inbox activity"
            st.save()
            self.stdout.write(self.style.SUCCESS("Woke from DORMANT (inbox activity)."))
        if pending:
            call_command("watch_reports", with_pdf=opts["with_pdf"])
            st.last_activity = timezone.now()
            st.save()
        call_command("cleanup_reports", days=7)
        # streak/badge evaluation (Phase 3.4, 2026-10-08)
        call_command("streak_check")
        # Kaifiyat_e_Mizan recompute + badges (v2.3, 2026-10-09).
        # MTSS/NCII progress monitoring cadence; ISO 9001:2015 9.1.2.
        # Fail-safe (Section 13.2 L6): a failure must not break cron_tick.
        try:
            call_command('recompute_kzm', '--all')
            call_command('badge_check')
        except Exception:
            pass
        # Task invariant scan (2026-10-11). Detects category / subject /
        # pipeline drift. Quiet when clean; loud when not.
        # Standards: NIST CSF DE.AE-2 (anomaly detection); COBIT BAI06
        # (change assurance); Rule 14; Rule 28. Fail-safe per Section 13.2 L6.
        try:
            call_command('check_task_invariants', quiet=True)
        except Exception:
            pass
        # Daily KC data quality scan (P13-10). Idempotent; runs at most
        # once per UTC day via --daily-only marker.
        # Standards: ISO 8000-8 (data quality); NIST CSF DE.AE-2 (anomaly
        # detection); Rule 28; Section 13.2 L6 (fail-safe).
        try:
            call_command('detect_kc_defects', daily_only=True)
        except Exception:
            pass
        # Hygiene: nightly + weekly clean, disk alert.
        # Standards: ISO 27001 A.8.10, A.8.13; DAMA-DMBOK2;
        # Section 13.2 L6 (fail-safe).
        try:
            if _should_run_period(base, "last_clean_nightly.txt", "day"):
                call_command("clean_nightly", apply=True)
            if _should_run_period(base, "last_clean_weekly.txt", "week"):
                call_command("clean_weekly", apply=True)
            _disk_alert(base, 80)
        except Exception:
            pass
        st.last_activity = timezone.now()
        st.save()
        self.stdout.write(self.style.SUCCESS("cron_tick complete."))


def _rotate_cron_log(base_dir, max_bytes=5 * 1024 * 1024):
    # Size-based rotation. Standards: logrotate copy-truncate.
    log = base_dir / "tmp" / "cron.log"
    if not log.exists():
        return
    try:
        if log.stat().st_size < max_bytes:
            return
    except OSError:
        return
    bak = log.with_suffix(".log.1")
    try:
        if bak.exists():
            bak.unlink()
        log.rename(bak)
    except OSError:
        pass


def _should_run_period(base, marker, period):
    """True if the marker does not already say we ran this period.
    Standards: Google SRE Ch.17 (idempotent jobs); ISO 9001 8.5.1;
    Twelve-Factor App."""
    from datetime import datetime, timezone
    m = base / "tmp" / marker
    now = datetime.now(timezone.utc)
    if period == "day":
        key = now.date().isoformat()
    else:
        iso = now.isocalendar()
        key = str(iso[0]) + "-W" + f"{iso[1]:02d}"
    if m.exists():
        try:
            if m.read_text(encoding="utf-8").strip() == key:
                return False
        except OSError:
            pass
    m.parent.mkdir(parents=True, exist_ok=True)
    m.write_text(key, encoding="utf-8")
    return True


def _disk_alert(base, threshold_pct=80):
    """Disk alert if usage exceeds threshold.
    Standards: ISO 27001 A.8.13 (capacity); NIST CSF DE.AE-2."""
    import json, shutil
    from datetime import datetime, timezone
    t, u, f = shutil.disk_usage(str(base))
    pct = int(100 * u / t)
    if pct >= threshold_pct:
        log = base / "tmp" / "disk_alert.jsonl"
        log.parent.mkdir(parents=True, exist_ok=True)
        with log.open("a", encoding="utf-8") as fh:
            fh.write(json.dumps({"ts": datetime.now(timezone.utc).isoformat(),
                                 "used_pct": pct,
                                 "free_gb": round(f/1e9,2)}) + "\n")
    return pct
