"""Read-only crest automation dashboard snapshot for the authenticated local app.

No service controls, shell arguments from requests, filesystem writes, or
background processes. Scheduler status can be unavailable independently of
the SQLite and controller state: never fabricate a positive status.
"""
from __future__ import annotations

from contextlib import closing
from datetime import datetime, timezone
import json
from pathlib import Path
import sqlite3
import subprocess
import threading
import time

BASE = Path(__file__).resolve().parent
DIAG = BASE.parent.parent / "FootballAnalytics_Diagnostics"
TASK = "Football Analytics - Verified Crest Backfill"
CACHE_SECONDS = 20
_LOCK = threading.RLock()
_CACHE = None
_CACHED_AT = 0.0


def _utc():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def _read_json(path):
    try:
        if path.stat().st_size > 1024 * 1024:
            raise ValueError("Oversized automation report")
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError, UnicodeError, TypeError):
        return None


def _integer(value, default=0):
    try:
        return max(0, int(value))
    except (ValueError, TypeError, OverflowError):
        return default


def _sql_count(path, sql, values=()):
    try:
        # SQLite URI mode=ro avoids creating any DB on a missing path.
        with closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=3)) as c:
            return _integer(c.execute(sql, values).fetchone()[0])
    except (OSError, sqlite3.Error, ValueError):
        return None


def _scheduler():
    # Literal task name and read-only PowerShell cmdlets. No request-derived input.
    command = (
        "$ErrorActionPreference='Stop';"
        "$n='Football Analytics - Verified Crest Backfill';"
        "$t=Get-ScheduledTask -TaskName $n;"
        "$i=Get-ScheduledTaskInfo -TaskName $n;"
        "[pscustomobject]@{"
        "state=[string]$t.State;"
        "lastRun=$i.LastRunTime.ToString('o');"
        "nextRun=$i.NextRunTime.ToString('o');"
        "lastResult=[int]$i.LastTaskResult"
        "}|ConvertTo-Json -Compress"
    )
    try:
        r = subprocess.run(
            ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command],
            capture_output=True, text=True, encoding="utf-8",
            errors="replace", timeout=8,
            creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0),
        )
        if r.returncode != 0:
            raise ValueError("Scheduler status unavailable")
        body = json.loads(r.stdout.strip())
        if not isinstance(body, dict) or body.get("state") not in (
            "Ready", "Running", "Disabled", "Queued"
        ):
            raise ValueError("Unrecognized task status")
        return {
            "available": True,
            "state": body["state"],
            "lastRun": body.get("lastRun"),
            "nextRun": body.get("nextRun"),
            "lastResult": body.get("lastResult"),
        }
    except (OSError, ValueError, subprocess.TimeoutExpired, json.JSONDecodeError):
        return {"available": False, "state": "Unknown", "lastRun": None,
                "nextRun": None, "lastResult": None}


def _latest_audit():
    try:
        paths = sorted(DIAG.glob("TeamIdentity_Crest_Backfill_Audit_*.json"),
                       key=lambda p: p.stat().st_mtime, reverse=True)
    except OSError:
        paths = []
    for p in paths[:5]:
        a = _read_json(p)
        if isinstance(a, dict) and isinstance(a.get("issues_count"), int):
            return {
                "verifiedAt": a.get("utc"),
                "issues": a["issues_count"],
                "assetsVerified": a.get("all_local_assets_verified") is True,
                "matches": _integer(a.get("match_count")),
                "status": "Passed" if (a["issues_count"] == 0 and
                         a.get("all_local_assets_verified") is True) else "Attention",
            }
    return {"verifiedAt": None, "issues": None,
            "assetsVerified": False, "matches": None, "status": "Unknown"}


def _build():
    s = _scheduler()
    state = _read_json(DIAG / "CREST_AUTORUN_STATE.json")
    if not isinstance(state, dict):
        state = {}
    last = state.get("last") if isinstance(state.get("last"), dict) else {}
    event = str(last.get("event") or "No recorded run")[:70]
    event_at = last.get("utc") if isinstance(last.get("utc"), str) else None
    flag = DIAG / "CREST_AUTORUN_PAUSED.flag"
    paused = flag.exists()
    try:
        reason = flag.read_text(encoding="utf-8") if paused else ""
    except OSError:
        reason = "Paused; reason file unavailable"
    # Avoid publishing exception tracebacks, local file paths or arbitrary text.
    reason = reason.strip().splitlines()[0][:120] if reason else ""
    teams = _sql_count(BASE / "team_identity_registry.db", "SELECT COUNT(*) FROM teams")
    crests = _sql_count(BASE / "team_identity_registry.db", "SELECT COUNT(*) FROM team_crests")
    bridges = _sql_count(BASE / "team_identity_registry.db",
                         "SELECT COUNT(*) FROM provider_ids WHERE provider=?",
                         ("api_football",))
    linked = _sql_count(BASE / "team_identity_registry.db",
                        "SELECT COUNT(*) FROM identity_audit WHERE action=?",
                        ("verified_api_football_country_exact_id_link",))
    rejected = _sql_count(BASE / "team_identity_registry.db",
                          "SELECT COUNT(*) FROM team_crest_rejections")
    quarantined = _sql_count(BASE / "team_identity_registry.db",
                             "SELECT COUNT(*) FROM team_crest_quarantine")
    logos = _sql_count(BASE / "football_analytics.db", "SELECT COUNT(*) FROM team_logos")
    matches = _sql_count(BASE / "football_analytics.db", "SELECT COUNT(*) FROM matches")
    usage = _sql_count(BASE / "soccerrating_logo_review.db",
                       "SELECT COUNT(*) FROM api_football_calls WHERE requested_at>?",
                       (int(time.time()) - 86400,))
    audit = _latest_audit()
    recent_success = None
    journal = DIAG / "CREST_AUTORUN_JOURNAL.jsonl"
    try:
        # Only a bounded tail of the journal: never send full sensitive history.
        with journal.open("rb") as f:
            f.seek(0, 2)
            end = f.tell()
            f.seek(max(0, end - 64 * 1024))
            chunk = f.read().decode("utf-8", errors="replace")
        for line in reversed(chunk.splitlines()):
            try:
                item = json.loads(line)
            except (ValueError, TypeError):
                continue
            if item.get("event") in ("BATCH_AUDIT_PASSED", "IDENTITY_ONLY_AUDIT_PASSED"):
                recent_success = {"utc": item.get("utc"),
                                  "event": item.get("event"),
                                  "country": str(item.get("country") or "")[:70],
                                  "crestsAdded": _integer(item.get("newly_assigned")),
                                  "identitiesLinked": _integer(item.get("newly_linked_source_ids"))}
                break
    except OSError:
        pass
    rate = round(crests / teams * 100, 2) if teams and crests is not None else None
    if paused:
        health = "Halted"
    elif not s["available"]:
        health = "Unknown"
    elif s["state"] == "Disabled":
        health = "Disabled"
    elif s["state"] == "Running":
        health = "Running"
    elif event in ("QUOTA_WAIT", "IDENTITY_QUOTA_WAIT"):
        health = "Quota wait"
    elif event == "HALTED_FOR_REVIEW":
        health = "Needs review"
    elif s["state"] == "Ready":
        health = "Scheduled"
    else:
        health = "Unknown"
    return {
        "ok": True, "asOf": _utc(), "scheduler": s,
        "controller": {
            "health": health, "latestEvent": event, "latestEventAt": event_at,
            "completedRuns": _integer(state.get("runs")), "paused": paused,
            "pauseReason": reason, "lastVerifiedBatch": recent_success,
        },
        "coverage": {
            "registeredTeams": teams, "assignedCrests": crests,
            "savedLogos": logos, "apiFootballLinks": bridges,
            "stage2Links": linked, "rejections": rejected,
            "quarantined": quarantined, "matches": matches,
            "percent": rate,
        },
        "quota": {
            "used24h": usage, "safeMax24h": 75,
            "controllerThreshold": 72,
            "controllerRemaining": max(0, 72 - usage) if usage is not None else None,
            "note": "Shared API quota; 3 requests reserved for importer",
        },
        "audit": audit,
    }


def status(force=False):
    global _CACHE, _CACHED_AT
    with _LOCK:
        t = time.monotonic()
        if not force and _CACHE is not None and t - _CACHED_AT < CACHE_SECONDS:
            return dict(_CACHE)
        data = _build()
        _CACHE, _CACHED_AT = data, time.monotonic()
        return dict(data)
