print("SERVER LOADED server.py")

import uvicorn
from fastapi import FastAPI, HTTPException, Request, UploadFile, File, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse, JSONResponse, HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
import hashlib
import json
import os
import sys
import tempfile

from orchestrator.routes.auth_utils import _check_auth
from orchestrator.archon_internal_bcd3a2f4e0b6f967.prom_integration import mount_internal, internal_preparation_response
from orchestrator.equilibra_pep import DEFAULT_SOCKET_PATH, evaluate_prom_mutation
from orchestrator.security import (
    SAFE_HTTP_METHODS,
    allowed_cors_origins,
    equilibra_route_enforcement_enabled,
    mutations_enabled,
    promac_scheduler_enabled,
    runtime_posture,
)

# ======================================================
# PATH NORMALIZATION
# ======================================================

FILE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(FILE_DIR, "../../"))

# Ensure project root is in path for module imports
if PROJECT_ROOT not in sys.path:
    sys.path.insert(0, PROJECT_ROOT)

print("\n[DEBUG PATHS]")
print("PROJECT_ROOT:", PROJECT_ROOT)
print("--------------------------------------------------\n")

# ======================================================
# FASTAPI APP CONFIG
# ======================================================

app = FastAPI(title="assistant tool HQ API")
mount_internal(app, _check_auth)

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_cors_origins(),
    allow_methods=["GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE"],
    allow_headers=["Content-Type", "X-Dispatcher-Token", "X-Equilibra-Request-ID"],
    allow_credentials=False,
)


@app.middleware("http")
async def _prom_mutation_gate(request: Request, call_next):
    """Default-deny every HTTP mutation before route-specific code runs."""
    if request.method.upper() not in SAFE_HTTP_METHODS:
        try:
            _check_auth(request.headers.get("X-Dispatcher-Token"))
        except HTTPException as exc:
            return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
        internal_response = await internal_preparation_response(request)
        if internal_response is not None:
            return internal_response
        if equilibra_route_enforcement_enabled():
            request_id = request.headers.get("X-Equilibra-Request-ID")
            if not request_id:
                return JSONResponse(
                    status_code=428,
                    content={
                        "detail": "an exact Equilibra Stage C admission is required",
                        "code": "equilibra_approval_required",
                    },
                )
            decision = evaluate_prom_mutation(
                request_id,
                method=request.method.upper(),
                path=request.url.path,
                socket_path=os.environ.get(
                    "HAIL_PROM_EQUILIBRA_SOCKET", DEFAULT_SOCKET_PATH
                ),
            )
            if not decision.available:
                return JSONResponse(
                    status_code=503,
                    content={
                        "detail": "Equilibra Stage C enforcement is unavailable",
                        "code": "equilibra_pep_unavailable",
                    },
                )
            if not decision.allowed:
                return JSONResponse(
                    status_code=403,
                    content={
                        "detail": "Equilibra Stage C admission did not reach policy eligibility",
                        "code": "equilibra_approval_parked",
                        "disposition": decision.disposition,
                        "reasons": list(decision.reasons),
                    },
                )
        if not mutations_enabled():
            return JSONResponse(
                status_code=423,
                content={
                    "detail": "PROM mutations are locked; a human-controlled service cutover is required",
                    "code": "prom_mutations_locked",
                },
            )
    return await call_next(request)

# ======================================================
# MODULE INITIALIZATION
# ======================================================

# ── Dispatch UI ──────────────────────────────────────────────────────────────
STATIC_DIR = os.path.join(FILE_DIR, "../static")
VIEWER_STATIC_DIR = os.path.expanduser("~/research collection/analysis/eva_reference/tools/anchor_ui")
VMS_STATIC_DIR = os.path.expanduser("~/research collection")

@app.get("/dispatch", response_class=HTMLResponse)
@app.get("/d", response_class=HTMLResponse)
async def dispatch_ui():
    with open(os.path.join(STATIC_DIR, "dispatch.html"), "r") as f:
        return HTMLResponse(content=f.read())

from orchestrator.routes.cat import router as cat_router
app.include_router(cat_router)

from orchestrator.routes.vms import router as vms_router
app.include_router(vms_router)

from orchestrator.routes.coviewer import router as coviewer_router
app.include_router(coviewer_router)

from orchestrator.routes.vms_llm import router as vms_llm_router
app.include_router(vms_llm_router)

from orchestrator.routes.vms_iiif import router as vms_iiif_router
from prometheus_chat_router import router as prom_chat_router
from orchestrator.routes.deepscan import router as deepscan_router
from orchestrator.routes.lattice import router as lattice_router
from orchestrator.routes.state import router as state_router
from orchestrator.routes.detached_jobs import router as detached_jobs_router
from orchestrator.routes.dispatcher import router as dispatcher_router
from orchestrator.routes.dispatch import router as dispatch_router
from orchestrator.routes.memory import router as memory_router
from orchestrator.routes.workspace import router as workspace_router
from orchestrator.routes.universal_dashboard import router as universal_dashboard_router
from orchestrator.routes.operation import router as operation_router
from orchestrator.routes.erv1_deterministic import router as erv1_deterministic_router
from orchestrator.api.slopfilter_bridge import build_slopfilter_router, legacy_slopfilter_gone_response
app.include_router(vms_iiif_router)

app.include_router(prom_chat_router)
app.include_router(deepscan_router)
app.include_router(lattice_router)
app.include_router(state_router)
app.include_router(detached_jobs_router)
app.include_router(dispatcher_router)
app.include_router(dispatch_router)
app.include_router(memory_router)
app.include_router(workspace_router)
app.include_router(universal_dashboard_router)
app.include_router(operation_router)
app.include_router(erv1_deterministic_router)
slopfilter_bridge_router = build_slopfilter_router()
if slopfilter_bridge_router is not None:
    app.include_router(slopfilter_bridge_router)

if os.path.isdir(VMS_STATIC_DIR):
    app.mount("/vms", StaticFiles(directory=VMS_STATIC_DIR), name="vms_static")

if os.path.isdir(VIEWER_STATIC_DIR):
    app.mount("/viewer", StaticFiles(directory=VIEWER_STATIC_DIR, html=True), name="viewer_static")


@app.get("/reader.html")
async def legacy_reader_redirect():
    return RedirectResponse(url="/viewer/?tab=viewer", status_code=307)

from modules.vms_os.runtime.voynich_os import VoynichOS
from modules.pce.runtime.pce import PCEngine
from modules.copycat.runtime.copycat import Copycat

vms = VoynichOS()
pce = PCEngine()
copycat = Copycat(os.path.join(PROJECT_ROOT, "modules/copycat/spec/COPYCAT_SPEC_V1.yaml"))

# ======================================================
# LLM ENDPOINTS
# ======================================================

@app.post("/api/llm")
async def llm_query(payload: dict):
    """Retained legacy surface that now points callers to dispatch."""
    return JSONResponse(
        status_code=410,
        content={
            "deprecated": True,
            "error": "gone",
            "message": "POST /api/llm has been retired. Use /api/dispatch.",
            "replacement": "/api/dispatch",
        },
    )


@app.post("/api/generate")
async def generate(payload: dict):
    """Ollama-compatible endpoint — used by myresearchadvisor extension."""
    prompt = payload.get("prompt", "").strip()
    model = payload.get("model", None)
    mode = payload.get("mode", "default")
    if not prompt:
        return {"error": "prompt required"}
    from orchestrator.services.keeper_dispatch import run_logged_dispatch
    from orchestrator.services.llm import (
        KVConfig,
        MODELS,
        _build_system_prompt_stack,
        compress_prompt,
        get_kernel,
    )
    if model:
        result = run_logged_dispatch(
            source="generate",
            connector="ollama",
            model=model,
            prompt=prompt,
            mode=mode,
        )
        return {"model": model, "mode": mode, "response": result["body"]}

    resolved_prompt = prompt
    kv_stats = None
    if mode == "kvcache_compressed":
        cfg = KVConfig()
        resolved_prompt, stats = compress_prompt(prompt, cfg)
        kv_stats = stats.log()

    system_prompt, layers = _build_system_prompt_stack(mode)
    resolved_model = MODELS.get(mode, MODELS["default"])
    result = run_logged_dispatch(
        source="generate",
        connector="ollama",
        model=resolved_model,
        prompt=resolved_prompt,
        mode=mode,
        system_prompt=system_prompt or None,
    )
    kernel = get_kernel().get("ED_MODE_KERNEL_PROFILE", {}).get("id") if isinstance(get_kernel(), dict) else None
    return {
        "model": resolved_model,
        "mode": mode,
        "response": result["body"],
        "kv_stats": kv_stats,
        "kernel": kernel,
        "layers_injected": layers,
    }

# ======================================================
# MODULE ENDPOINTS
# ======================================================

@app.post("/api/ocr")
async def run_ocr(file: UploadFile = File(...)):
    """OCR extraction using Tesseract via diagram_ocr module."""
    try:
        from modules.vms_os.runtime_advanced.diagram_ocr import extract_text_from_image
        # Save uploaded file to temp location
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp:
            tmp.write(await file.read())
            tmp_path = tmp.name
        result = extract_text_from_image(tmp_path)
        os.unlink(tmp_path)
        return result
    except Exception as e:
        return {"error": str(e), "text": ""}


@app.post("/api/glyphs")
async def glyph_extract(file: UploadFile = File(...)):
    """Extract glyphs from uploaded manuscript image."""
    try:
        from modules.vms_os.runtime_advanced.glyph_extractor import extract_glyphs, extract_glyph_features
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp:
            tmp.write(await file.read())
            tmp_path = tmp.name
        raw_glyphs = extract_glyphs(tmp_path)
        features = extract_glyph_features(raw_glyphs)
        os.unlink(tmp_path)
        return {"filename": file.filename, "glyphs_detected": len(raw_glyphs), "segments": features}
    except Exception as e:
        return {"filename": file.filename, "glyphs_detected": 0, "segments": [], "error": str(e)}


@app.post("/api/adj")
async def adjacency(payload: dict):
    """Build adjacency graph from text or operator sequence."""
    text = payload.get("text", "").strip()
    if not text:
        return {"edges": [], "count": 0}

    # Run through VoynichOS for operator-level adjacency
    analysis = vms.analyze(text)
    edges = analysis["adjacency"]["edges"]

    return {
        "edges": edges,
        "count": len(edges),
        "matrix": analysis["adjacency"]["matrix"],
        "labels": analysis["adjacency"]["matrix_labels"],
        "stats": analysis["stats"],
    }


@app.post("/api/volvelles")
async def volvelles(payload: dict):
    """Detect periodicities in operator sequences or point data."""
    text = payload.get("text", "")
    points = payload.get("points", None)

    result = {}

    if text:
        analysis = vms.analyze(text)
        result["operator_periodicity"] = analysis["periodicity"]

    if points:
        from modules.vms_os.runtime_advanced.volvelle_periodicity import detect_ring_structure
        import numpy as np
        result["ring_structure"] = detect_ring_structure(np.array(points))

    if not result:
        result = {"periodicities": {"C12": False, "C6": False, "C2": False}}

    return result


@app.post("/api/voynich")
async def vms_analysis(payload: dict):
    """Full Voynich OS analysis pipeline."""
    text = payload.get("text", "")
    if not text:
        return {"error": "text required"}
    return vms.analyze(text)


@app.post("/api/slopfilter", deprecated=True)
async def slopfilter():
    """Retained legacy surface that now points callers to the public bridge."""
    return legacy_slopfilter_gone_response()


@app.post("/api/copycat")
async def copycat_endpoint(payload: dict):
    """Copycat provenance hashing and watermarking."""
    text = payload.get("text", "")
    result = copycat.fingerprint(text)
    watermarked = copycat.watermark(text)
    return {
        "sha256": result["sha256"],
        "sha1": result.get("sha1", ""),
        "md5": result.get("md5", ""),
        "watermarked": watermarked,
    }


@app.post("/api/pce")
async def pce_analysis(payload: dict):
    """PCE (Padua Consolidation Engine) — cross-tradition medical text analysis."""
    text = payload.get("text", "").strip()
    if not text:
        return {"error": "text required"}

    H = payload.get("H_state", None)
    C = payload.get("C_band", None)
    G = payload.get("G_role", None)

    return pce.analyze(text, H=H, C=C, G=G)


@app.post("/api/pce/route")
async def pce_route(payload: dict):
    """PCE tradition routing for a specific H/C/G combination."""
    return pce.route(
        payload.get("H_state", "unknown"),
        payload.get("C_band", "unclassified"),
        payload.get("G_role", "general"),
    )


@app.post("/api/pce/concordance")
async def pce_concordance(payload: dict):
    """PCE cross-tradition concordance for input text."""
    text = payload.get("text", "").strip()
    if not text:
        return {"error": "text required"}
    return pce.concordance(text)


# ======================================================
# DATA ENDPOINTS
# ======================================================

@app.get("/api/db/stats")
async def db_stats():
    """Return VMS database statistics including abbreviation data."""
    import sqlite3
    db_path = os.path.join(PROJECT_ROOT, "data", "voynich_db", "vms.db")
    if not os.path.exists(db_path):
        return {"error": "Database not initialized. Run: python data/ingest_vms.py --init"}

    conn = sqlite3.connect(db_path)
    stats = {
        "folios": conn.execute("SELECT COUNT(*) FROM folios").fetchone()[0],
        "transcriptions": conn.execute("SELECT COUNT(*) FROM transcriptions").fetchone()[0],
        "glyph_sequences": conn.execute("SELECT COUNT(*) FROM glyph_sequences").fetchone()[0],
        "analysis_results": conn.execute("SELECT COUNT(*) FROM analysis_results").fetchone()[0],
    }

    # Abbreviation stats
    for table in ["abbreviations", "operators", "stems", "suffixes", "pharma_vocab", "cappelli_plates"]:
        try:
            stats[table] = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
        except Exception:
            pass

    sections = conn.execute(
        "SELECT section, COUNT(*) as c FROM folios WHERE section != '' GROUP BY section ORDER BY c DESC"
    ).fetchall()
    stats["sections"] = {row[0]: row[1] for row in sections}

    conn.close()
    return stats


@app.get("/api/db/search")
async def db_search(q: str):
    """Search across all abbreviation/lexicon tables."""
    import sqlite3
    db_path = os.path.join(PROJECT_ROOT, "data", "voynich_db", "vms.db")
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row
    term = f"%{q}%"
    results = {}

    try:
        rows = conn.execute(
            "SELECT form, expansion, meaning_en, category, source, confidence FROM abbreviations WHERE form LIKE ? OR expansion LIKE ? OR meaning_en LIKE ?",
            (term, term, term)).fetchall()
        if rows:
            results["abbreviations"] = [dict(r) for r in rows]
    except Exception:
        pass

    try:
        rows = conn.execute(
            "SELECT form, meaning_en, meaning_hr, confidence, count FROM operators WHERE form LIKE ? OR meaning_en LIKE ?",
            (term, term)).fetchall()
        if rows:
            results["operators"] = [dict(r) for r in rows]
    except Exception:
        pass

    try:
        rows = conn.execute(
            "SELECT form, meaning_en, meaning_hr, latin, category, confidence FROM stems WHERE form LIKE ? OR meaning_en LIKE ? OR meaning_hr LIKE ?",
            (term, term, term)).fetchall()
        if rows:
            results["stems"] = [dict(r) for r in rows[:50]]
    except Exception:
        pass

    try:
        rows = conn.execute(
            "SELECT voynich_form, latin, meaning, category, count, key_folios FROM pharma_vocab WHERE voynich_form LIKE ? OR latin LIKE ? OR meaning LIKE ?",
            (term, term, term)).fetchall()
        if rows:
            results["pharma_vocab"] = [dict(r) for r in rows]
    except Exception:
        pass

    conn.close()
    results["query"] = q
    results["total_matches"] = sum(len(v) for v in results.values() if isinstance(v, list))
    return results


@app.get("/api/db/folios")
async def db_folios(section: str = None):
    """List folios, optionally filtered by section."""
    import sqlite3
    db_path = os.path.join(PROJECT_ROOT, "data", "voynich_db", "vms.db")
    conn = sqlite3.connect(db_path)
    conn.row_factory = sqlite3.Row

    if section:
        rows = conn.execute("SELECT * FROM folios WHERE section = ? ORDER BY folio_id", (section,)).fetchall()
    else:
        rows = conn.execute("SELECT * FROM folios ORDER BY folio_id").fetchall()

    conn.close()
    return [dict(r) for r in rows]


# ======================================================
# STATUS + LOGS
# ======================================================

@app.get("/api/status")
async def status():
    """System health check — verify all modules and backends."""
    module_status = {
        "VoynichOS": "loaded",
        "PCEngine": "loaded",
        "SlopFilter": "loaded",
        "Copycat": "loaded",
    }

    # Check Ollama
    try:
        import requests as req
        r = req.get("retained local service", timeout=3)
        models = [m["name"] for m in r.json().get("models", [])]
        ollama_status = {"status": "running", "models": models}
    except Exception:
        ollama_status = {"status": "offline", "models": []}

    # Check DB
    db_path = os.path.join(PROJECT_ROOT, "data", "voynich_db", "vms.db")
    db_status = "initialized" if os.path.exists(db_path) else "not initialized"

    return {
        "status": "OK",
        "modules": module_status,
        "ollama": ollama_status,
        "database": db_status,
    }


@app.get("/api/state/snapshot")
async def state_snapshot():
    """Structural ground-truth view of assistant tool state.

    Consumed by AC's briefing builder (and future reader nodes) to avoid
    state drift between AC's snapshot and what CC-U has actually built.
    One call, one view, no interpolation. See CAT msg id 7 for rationale.
    """
    from datetime import datetime
    from pathlib import Path as _P
    import subprocess as _sub

    snap = {
        "timestamp": datetime.now().isoformat(),
        "tasks": {},
        "messages": {},
        "sessions": {},
        "llm": {},
        "promac": {},
        "extractions": {},
        "services": {},
    }

    # ── Tasks / Messages / CAT sessions (single DB connection) ────────
    try:
        from orchestrator.routes.cat import get_db
        conn = get_db()
        try:
            cur = conn.cursor()

            # Task counts by status
            cur.execute("SELECT status, COUNT(*) FROM cat_tasks GROUP BY status")
            counts = {row[0]: row[1] for row in cur.fetchall()}

            cur.execute(
                "SELECT id, title, assigned_to, priority, created_by, created_at "
                "FROM cat_tasks WHERE status='pending' "
                "ORDER BY priority ASC, created_at DESC LIMIT 10"
            )
            pending = [
                {"id": r[0], "title": r[1], "assigned_to": r[2],
                 "priority": r[3], "created_by": r[4], "created_at": r[5]}
                for r in cur.fetchall()
            ]

            cur.execute(
                "SELECT id, title, assigned_to, updated_at "
                "FROM cat_tasks WHERE status='in_progress' "
                "ORDER BY updated_at DESC LIMIT 10"
            )
            in_prog = [
                {"id": r[0], "title": r[1], "assigned_to": r[2], "updated_at": r[3]}
                for r in cur.fetchall()
            ]

            cur.execute(
                "SELECT id, title, assigned_to, updated_at "
                "FROM cat_tasks WHERE status='completed' "
                "ORDER BY updated_at DESC LIMIT 5"
            )
            completed = [
                {"id": r[0], "title": r[1], "assigned_to": r[2], "updated_at": r[3]}
                for r in cur.fetchall()
            ]

            snap["tasks"] = {
                "counts": counts,
                "pending": pending,
                "in_progress": in_prog,
                "recent_completed": completed,
            }

            # Recent CAT messages
            cur.execute(
                "SELECT id, timestamp, from_member, content, tags "
                "FROM cat_messages ORDER BY id DESC LIMIT 20"
            )
            msgs = []
            for r in cur.fetchall():
                content = (r[3] or "")
                if len(content) > 400:
                    content = content[:400] + "…"
                try:
                    tags = json.loads(r[4] or "[]")
                except Exception:
                    tags = []
                msgs.append({
                    "id": r[0], "timestamp": r[1], "from": r[2],
                    "content": content, "tags": tags,
                })
            snap["messages"] = {"recent": msgs, "count_returned": len(msgs)}

            # CAT sessions (coordination layer, not PROM chat sessions)
            cur.execute(
                "SELECT id, timestamp, session_id, crew_member "
                "FROM cat_sessions ORDER BY id DESC LIMIT 5"
            )
            cat_sess = [
                {"id": r[0], "timestamp": r[1], "session_id": r[2], "crew_member": r[3]}
                for r in cur.fetchall()
            ]
            snap["sessions"]["cat"] = cat_sess
        finally:
            conn.close()
    except Exception as e:
        snap["tasks"] = snap.get("tasks") or {"error": str(e)}
        snap["messages"] = snap.get("messages") or {"error": str(e)}
        snap["sessions"]["cat_error"] = str(e)

    # ── PROM chat sessions (file-based) ────────────────────────────────
    try:
        prom_sess_dir = _P(PROJECT_ROOT) / "data" / "sessions"
        if prom_sess_dir.exists():
            files = sorted(
                prom_sess_dir.glob("*.json"),
                key=lambda p: p.stat().st_mtime,
                reverse=True
            )[:5]
            prom_sess = []
            for f in files:
                try:
                    data = json.loads(f.read_text())
                    prom_sess.append({
                        "session_id": data.get("session_id"),
                        "created_at": data.get("created_at"),
                        "updated_at": data.get("updated_at"),
                        "message_count": len(data.get("messages", [])),
                    })
                except Exception:
                    pass
            snap["sessions"]["prom_chat"] = prom_sess
        else:
            snap["sessions"]["prom_chat"] = []
    except Exception as e:
        snap["sessions"]["prom_chat_error"] = str(e)

    # ── LLM backends (Ollama) ──────────────────────────────────────────
    try:
        import requests as _req
        r = _req.get("retained local service", timeout=3)
        models = [m["name"] for m in r.json().get("models", [])]
        snap["llm"]["ollama"] = {"status": "running", "models": models}
    except Exception as e:
        snap["llm"]["ollama"] = {"status": "offline", "error": str(e)}

    # ── Promac (PROM → AC) state ───────────────────────────────────────
    try:
        from orchestrator.services import promac as _promac
        snap["promac"] = _promac.get_state()
    except Exception as e:
        snap["promac"] = {"error": str(e)}

    # ── On-disk extractions (BSB, Bodleian, etc.) ──────────────────────
    try:
        ext_dir = _P.home() / "hail" / "vms" / "extracted"
        ext = {}
        if ext_dir.exists():
            for sub in ext_dir.iterdir():
                if sub.is_dir() and sub.name.startswith("PATTERN_HITS_"):
                    files = [f for f in sub.rglob("*") if f.is_file()]
                    total_bytes = sum(f.stat().st_size for f in files)
                    ext[sub.name] = {
                        "files": len(files),
                        "bytes": total_bytes,
                        "mb": round(total_bytes / (1024 * 1024), 1),
                    }
        snap["extractions"] = ext
    except Exception as e:
        snap["extractions"] = {"error": str(e)}

    # ── Services (tailscale, assistant tool itself, modules) ───────────────
    try:
        r = _sub.run(["tailscale", "ip", "-4"],
                     capture_output=True, text=True, timeout=3)
        snap["services"]["tailscale_ip4"] = r.stdout.strip() if r.returncode == 0 else None
    except Exception:
        snap["services"]["tailscale_ip4"] = None

    snap["services"]["prometheus_api"] = "running"
    snap["services"]["modules_loaded"] = ["VoynichOS", "PCEngine", "SlopFilter", "Copycat"]

    # ── Work orders (audit log + manifest summaries) ───────────────────
    try:
        from collections import Counter as _Counter
        wo_dir = _P.home() / "hail" / "work_orders"
        wos = {}
        if wo_dir.exists():
            for wo in sorted(wo_dir.iterdir()):
                if not wo.is_dir():
                    continue
                wo_info = {"path": str(wo)}

                # audit_log.json — what the executor has actually done
                audit = wo / "audit_log.json"
                if audit.exists():
                    try:
                        entries = json.loads(audit.read_text())
                        if isinstance(entries, list) and entries:
                            counts = _Counter(e.get("status", "?") for e in entries)
                            wo_info["audit_log"] = {
                                "total": len(entries),
                                "counts": dict(counts),
                                "first": entries[0].get("timestamp"),
                                "last": entries[-1].get("timestamp"),
                            }
                        elif isinstance(entries, list):
                            wo_info["audit_log"] = {"total": 0, "counts": {}}
                        else:
                            wo_info["audit_log"] = {"error": "not a list"}
                    except Exception as e:
                        wo_info["audit_log"] = {"error": str(e)}

                # rename_manifest.json — what the executor plans
                manifest = wo / "rename_manifest.json"
                if manifest.exists():
                    try:
                        m = json.loads(manifest.read_text())
                        if isinstance(m, list):
                            wo_info["manifest"] = {
                                "total": len(m),
                                "status_counts": dict(_Counter(r.get("status", "?") for r in m)),
                            }
                    except Exception as e:
                        wo_info["manifest"] = {"error": str(e)}

                # deletion_log.json — for non-rename work order actions
                deletion = wo / "deletion_log.json"
                if deletion.exists():
                    try:
                        d = json.loads(deletion.read_text())
                        if isinstance(d, list):
                            wo_info["deletion_log"] = {
                                "total": len(d),
                                "counts": dict(_Counter(e.get("status", "?") for e in d)),
                            }
                    except Exception as e:
                        wo_info["deletion_log"] = {"error": str(e)}

                # Any README or phase review file (just note presence + mtime)
                reviews = (
                    sorted(wo.glob("PHASE*_REVIEW.md"))
                    + sorted(wo.glob("phase*_proposals.md"))
                    + sorted(wo.glob("phase*_review_list.md"))
                )
                if reviews:
                    wo_info["review_files"] = [
                        {"name": r.name, "bytes": r.stat().st_size,
                         "mtime": datetime.fromtimestamp(r.stat().st_mtime).isoformat()}
                        for r in reviews
                    ]

                wos[wo.name] = wo_info
        snap["work_orders"] = wos
    except Exception as e:
        snap["work_orders"] = {"error": str(e)}

    return snap


# ── PROM → AC channel ────────────────────────────────────────────────────────
from orchestrator.services import promac
from pydantic import BaseModel as _BM


class _PromacTriggerReq(_BM):
    trigger: str = "manual"


@app.post("/api/promac/trigger")
async def promac_trigger(req: _PromacTriggerReq):
    """Run an AC briefing on demand."""
    return await promac.run_briefing(trigger=req.trigger)


@app.get("/api/promac/status")
async def promac_status():
    """Scheduler + last-run state."""
    return promac.get_state()


@app.get("/api/security/posture")
async def security_posture():
    """Expose non-secret effective locks for the operator control surface."""
    posture = runtime_posture()
    return {
        "mutations_enabled": posture.mutations,
        "equilibra_route_enforcement_enabled": equilibra_route_enforcement_enabled(),
        "dispatcher_execution_enabled": posture.dispatcher_execution,
        "detached_jobs_enabled": posture.detached_jobs,
        "external_egress_enabled": posture.external_egress,
        "promac_scheduler_enabled": posture.promac_scheduler,
    }


@app.get("/api/promac/briefings")
async def promac_briefings(limit: int = 20):
    """List recent briefing files."""
    files = sorted(promac.BRIEFINGS_DIR.glob("AC_briefing_*.md"), reverse=True)[:limit]
    out = []
    for f in files:
        out.append({
            "name": f.name,
            "path": str(f),
            "size": f.stat().st_size,
            "mtime": f.stat().st_mtime,
        })
    return {"briefings": out}


@app.get("/api/promac/briefings/{name}")
async def promac_briefing_get(name: str):
    """Return contents of a single briefing."""
    # Path safety: only allow files in BRIEFINGS_DIR matching the pattern
    if not name.startswith("AC_briefing_") or "/" in name or "\\" in name:
        return JSONResponse({"error": "invalid name"}, status_code=400)
    f = promac.BRIEFINGS_DIR / name
    if not f.exists():
        return JSONResponse({"error": "not found"}, status_code=404)
    return PlainTextResponse(f.read_text())


@app.on_event("startup")
async def _startup_promac_scheduler():
    if promac_scheduler_enabled():
        promac.start_scheduler()


@app.on_event("shutdown")
async def _shutdown_promac_scheduler():
    promac.stop_scheduler()


@app.get("/api/logs")
async def logs():
    log_file = os.path.join(PROJECT_ROOT, "hq_logs.txt")
    if not os.path.exists(log_file):
        return PlainTextResponse("[No logs yet]")
    return PlainTextResponse(open(log_file).read())


# ======================================================
# CO-VIEWER RELAY — real-time bridge between CC and browser
# ======================================================

import asyncio
from datetime import datetime
from pydantic import BaseModel
from typing import Optional
from orchestrator.services import coview_db

coview_db.init_db()

class CoviewCommand(BaseModel):
    action: str                # highlight, replace_highlights, note, load, enhance, clear, stroke, arrow
    session_id: Optional[str] = "terminal"
    x: Optional[int] = None
    y: Optional[int] = None
    w: Optional[int] = None
    h: Optional[int] = None
    x1: Optional[int] = None
    y1: Optional[int] = None
    x2: Optional[int] = None
    y2: Optional[int] = None
    label: Optional[str] = ""
    text: Optional[str] = ""
    color: Optional[str] = "#ff6600"
    folio: Optional[str] = None
    mode: Optional[str] = None
    owner: Optional[str] = "claude"
    points: Optional[list] = None
    width: Optional[int] = None
    highlights: Optional[list] = None

# Per-session state + WS client pool. Sessions are lazily loaded from SQLite.
class _Session:
    __slots__ = ("id", "state", "clients")
    def __init__(self, sid: str):
        self.id = sid
        self.state = coview_db.load_session(sid)
        self.clients: list[WebSocket] = []

_sessions: dict[str, _Session] = {}


def _get_session(sid: str) -> _Session:
    s = _sessions.get(sid)
    if s is None:
        s = _Session(sid)
        _sessions[sid] = s
    return s


def _make_broadcaster(session: _Session):
    async def _broadcast(msg: dict):
        dead = []
        for ws in session.clients:
            try:
                await ws.send_json(msg)
            except Exception:
                dead.append(ws)
        for ws in dead:
            if ws in session.clients:
                session.clients.remove(ws)
    return _broadcast


@app.websocket("/api/coview/ws")
async def coview_websocket(ws: WebSocket):
    if not mutations_enabled():
        await ws.close(code=1008, reason="PROM mutations are locked")
        return
    sid = ws.query_params.get("session") or "terminal"
    await ws.accept()
    session = _get_session(sid)
    session.clients.append(ws)
    broadcast = _make_broadcaster(session)

    # Send current state on connect
    await ws.send_json({"action": "state", **session.state})
    try:
        while True:
            data = await ws.receive_json()
            data.setdefault("owner", "ed")
            data.setdefault("time", datetime.now().strftime("%H:%M:%S"))
            folio_changed = _process_command(session, data)

            # Broadcast to all OTHER clients in this session
            for other in session.clients:
                if other is not ws:
                    try: await other.send_json(data)
                    except: pass

            # On folio change, push a fresh state frame to every client
            # (hydrates the new folio's saved annotations from DB).
            if folio_changed or data.get("action") == "replace_highlights":
                await broadcast({"action": "state", **session.state})

            # Server-side Claude consumer
            if (data.get("action") == "note"
                    and data.get("owner") not in ("claude", "system")):
                from orchestrator.services.coview_consumer import respond_to_note
                asyncio.create_task(respond_to_note(session.state, data, broadcast, session_id=sid))
    except WebSocketDisconnect:
        if ws in session.clients:
            session.clients.remove(ws)


def _process_command(session: _Session, cmd: dict) -> bool:
    """Update session state from a command. Returns True if the folio changed
    (so caller can push a fresh state frame)."""
    state = session.state
    sid = session.id
    action = cmd.get("action", "")
    folio = state.get("folio", "f1r")

    if action == "highlight":
        state["highlights"].append(cmd)
        coview_db.save_highlight(sid, folio, cmd)
    elif action == "replace_highlights":
        normalized = []
        for hl in cmd.get("highlights") or []:
            normalized.append(
                {
                    "action": "highlight",
                    "type": hl.get("type", "rect"),
                    "x": int(hl.get("x", 0)),
                    "y": int(hl.get("y", 0)),
                    "w": int(hl.get("w", 0)),
                    "h": int(hl.get("h", 0)),
                    "label": hl.get("label") or "",
                    "owner": hl.get("owner") or cmd.get("owner") or "ed",
                    "color": hl.get("color") or "#00ccff",
                    "time": hl.get("time") or datetime.now().strftime("%H:%M:%S"),
                }
            )
        state["highlights"] = normalized
        coview_db.replace_highlights(sid, folio, normalized)
    elif action == "note":
        state["notes"].append(cmd)
        if len(state["notes"]) > 300:
            state["notes"] = state["notes"][-300:]
        coview_db.save_note(sid, cmd)
    elif action == "load":
        new_folio = cmd.get("folio", folio)
        if new_folio != folio:
            coview_db.set_folio(sid, new_folio)
            # Re-materialize annotations for the new folio
            fresh = coview_db.load_session(sid)
            state["folio"] = fresh["folio"]
            state["highlights"] = fresh["highlights"]
            state["strokes"] = fresh["strokes"]
            state["arrows"] = fresh["arrows"]
            # notes are session-global, keep them
            return True
    elif action == "stroke":
        state["strokes"].append(cmd)
        coview_db.save_stroke(sid, folio, cmd)
    elif action == "arrow":
        state["arrows"].append(cmd)
        coview_db.save_arrow(sid, folio, cmd)
    elif action == "clear":
        state["highlights"] = []
        state["strokes"] = []
        state["arrows"] = []
        coview_db.clear_annotations(sid, folio)
    return False


@app.post("/api/coview/command")
async def coview_command(cmd: CoviewCommand):
    """CC pushes commands here — they get broadcast to all WS clients in the
    same session. `session_id` defaults to 'terminal' for backwards-compat."""
    msg = cmd.dict()
    msg["time"] = datetime.now().strftime("%H:%M:%S")
    sid = msg.pop("session_id", None) or "terminal"
    session = _get_session(sid)
    folio_changed = _process_command(session, msg)
    broadcast = _make_broadcaster(session)
    await broadcast(msg)
    if folio_changed or msg.get("action") == "replace_highlights":
        await broadcast({"action": "state", **session.state})
    # Consumer trigger from HTTP path too
    if msg.get("action") == "note" and msg.get("owner") not in ("claude", "system"):
        from orchestrator.services.coview_consumer import respond_to_note
        asyncio.create_task(respond_to_note(session.state, msg, broadcast, session_id=sid))
    return {"ok": True, "clients": len(session.clients), "session": sid}


@app.get("/api/coview/state")
async def coview_state(session: str = "terminal"):
    """Read a session's current co-viewer state."""
    s = _get_session(session)
    return s.state


@app.get("/api/coview/sessions")
async def coview_sessions():
    """List sessions assistant tool has active in-memory + their client counts."""
    return [
        {
            "id": s.id,
            "clients": len(s.clients),
            "folio": s.state.get("folio"),
            "notes": len(s.state.get("notes", [])),
            "highlights": len(s.state.get("highlights", [])),
        }
        for s in _sessions.values()
    ]


# ======================================================
# LAUNCH
# ======================================================

if __name__ == "__main__":
    uvicorn.run(
        "orchestrator.api.server:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )
