#!/usr/bin/env python3
"""Full status check for AverysArtJourney."""
import sqlite3, json, os
from pathlib import Path

print("╔══════════════════════════════════════════════════════════════╗")
print("║  AVERYARTJOURNEY — FULL STATUS CHECK                          ║")
print("╚══════════════════════════════════════════════════════════════╝\n")

here = Path("/Users/brians/Documents/AveryArt")

# ── Phase 1 & 2: Certification Spine ──────────────────────────────────
print("── Phase 1+2: Certification Spine ──")
sys_path = str(here)
import sys
sys.path.insert(0, str(here))
from certification_spine import CertificationEngine, DEFAULT_DB

eng = CertificationEngine(DEFAULT_DB)
conn = sqlite3.connect(DEFAULT_DB)

states = conn.execute("SELECT state, COUNT(*) FROM facts GROUP BY state").fetchall()
print("Facts by state:", "  ".join(f"{s}={c}" for s, c in states))
n_galleries = conn.execute("SELECT COUNT(DISTINCT gallery_id) FROM facts").fetchone()[0]
n_t4_leaked = conn.execute(
    "SELECT COUNT(*) FROM facts WHERE source_tier=4 AND state='CERTIFIED'"
).fetchone()[0]
print(f"Galleries: {n_galleries}   T4 leaked: {n_t4_leaked} (must be 0)")

tiers = {}
for t in range(1, 6):
    cnt = conn.execute(f"SELECT COUNT(*) FROM facts WHERE source_tier={t}").fetchone()[0]
    tiers[t] = cnt
print(f"Tier breakdown: T1={tiers[1]}  T2={tiers[2]}  T3={tiers[3]}  T4={tiers[4]}  T5={tiers[5]}  TOTAL={sum(tiers.values())}")
ortuzar = conn.execute(
    "SELECT COUNT(*) FROM facts WHERE gallery_id='ortuzar' AND fact_class='comp_language'"
).fetchone()[0]
print(f"Ortuzar comp (Qualified anchor): {'YES ✓' if ortuzar else 'NO ✗'}")
conn.close()
print()

# ── Phase 3: Agent Profiles ────────────────────────────────────────────
print("── Phase 3: Agent Fleet ──")
profiles = ["scout", "ledger", "curator", "cartographer", "coach", "closer", "athena"]
for p in profiles:
    soules = list(Path(f"/Users/brians/.hermes/profiles/{p}").glob("*"))
    print(f"  {p:<12} {'✓' if any(soules) else '✗'}  {len(soules)} files")
print()

# ── Phase 3b: Drill Deck ───────────────────────────────────────────────
print("── Phase 3b: Drill Deck (deck_data.json) ──")
deck_path = here / "deck_data.json"
if deck_path.exists():
    cards = json.loads(deck_path.read_text())
    print(f"  deck_data.json: {len(cards)} cards")
    cats = {}
    for c in cards:
        cats[c["d"]] = cats.get(c["d"], 0) + 1
    for k, v in sorted(cats.items()):
        print(f"    {k:<18} {v} cards")
else:
    print("  deck_data.json: NOT FOUND")
print()

# ── Phase 4: Pipeline Board ────────────────────────────────────────────
print("── Phase 4: Pipeline Board ──")
pb_db = here / "avery_pipeline.db"
if pb_db.exists():
    conn = sqlite3.connect(pb_db)
    wips = [("Universe", None), ("Qualified", 25), ("Prepared", 8),
            ("Visited", 8), ("Contact", 5), ("Applied", 5),
            ("Interview", 3), ("Offer", None), ("Closed", None)]
    for col, wip in wips:
        cnt = conn.execute(
            "SELECT COUNT(*) FROM packets WHERE column=? AND status IN ('open','claimed','in_progress')",
            (col,),
        ).fetchone()[0]
        wip_str = "∞" if wip is None else wip
        mark = "✓" if (wip is None or cnt <= wip) else "✗ OVER WIP"
        print(f"  {col:<12} {cnt}/{wip_str} slots  {mark}")
    total = conn.execute("SELECT COUNT(*) FROM packets").fetchone()[0]
    print(f"  Total packets: {total}")
    conn.close()
else:
    print("  avery_pipeline.db: NOT FOUND")
print()

# ── Summary ────────────────────────────────────────────────────────────
print("── Summary ──")
checks = {
    "T4 quarantine intact (0 leaked)": n_t4_leaked == 0,
    "Ortuzar comp in spine (Qualified anchor)": ortuzar > 0,
    "All 7 profiles present": all(
        (Path(f"/Users/brians/.hermes/profiles/{p}")).exists()
        for p in profiles
    ),
    "65-card deck parsed": deck_path.exists() and len(json.loads(deck_path.read_text())) == 65,
    "Pipeline board seeded (13 packets)": pb_db.exists() and conn.execute("SELECT COUNT(*) FROM packets").fetchone()[0] == 13 if pb_db.exists() else False,
}
all_ok = True
for name, ok in checks.items():
    print(f"  {'✓' if ok else '✗'}  {name}")
    if not ok:
        all_ok = False
print(f"\nOverall: {'ALL CHECKS PASS ✓' if all_ok else 'SOME CHECKS FAILED ✗'}")
