"""Flask app: REST API + server-rendered dashboard.

Run with:  python app.py     (listens on 0.0.0.0:3000)
"""

from __future__ import annotations

import hashlib
import io
import json
import logging
import os
import tarfile

from flask import Flask, Response, jsonify, redirect, render_template, request, url_for

from orchestrator import audit
from orchestrator import bot_factory
from orchestrator.command_center import CommandCenter, command_center_blueprint
from orchestrator import ingestion
from orchestrator import measurement
from orchestrator import opportunity
from orchestrator import state_machine as sm
from orchestrator import verification
from orchestrator.components import register_default_components
from orchestrator.db import connect as db_connect, init_db
from orchestrator.errors import (
    BotBuildBlocked,
    JobNotFound,
    MeasurementBlocked,
    OrchestratorError,
    ValidationError,
    VerificationBlocked,
)
from orchestrator.registry import REGISTRY
from orchestrator import service
from orchestrator import memory
from orchestrator import scheduling
from orchestrator import voice
from orchestrator import avatar
from orchestrator import pwa
from orchestrator import live_data
from orchestrator import live_ingest
from orchestrator import mapbox_source
from orchestrator import secrets_vault
from orchestrator import secrets as secrets_api
from orchestrator import heartbeat
from orchestrator import outreach
from orchestrator import scheduler_loop

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)-7s %(name)s: %(message)s",
)
log = logging.getLogger("jarvis.app")

#: Root of the project tree, i.e. the source that /snapshot.tar.gz packs up.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

#: Source snapshot: what goes in, and what is deliberately left out.
SNAPSHOT_INCLUDE_SUFFIXES = (".py", ".html", ".txt", ".md")
SNAPSHOT_INCLUDE_NAMES = {".gitignore"}
SNAPSHOT_EXCLUDE_DIRS = {"__pycache__", ".git", ".pytest_cache", ".mypy_cache",
                         "node_modules", ".venv", "venv"}
SNAPSHOT_EXCLUDE_SUFFIXES = (".db", ".db-wal", ".db-shm", ".pyc", ".pyo", ".log")
SNAPSHOT_EXCLUDE_NAMES = {".env"}

# ---------------------------------------------------------------------------
# TEMPORARY SOURCE EXPORT (to be deleted once the source has been copied out).
# Chunked JSON export so the tree can be pulled over plain HTTP, part by part.
# ---------------------------------------------------------------------------
#: TEMPORARY: only these file types are exported.
EXPORT_INCLUDE_SUFFIXES = (".py", ".html", ".css", ".js", ".md", ".txt",
                           ".json", ".toml", ".cfg", ".ini", ".webmanifest")
#: TEMPORARY: never walked into.
EXPORT_EXCLUDE_DIRS = {"__pycache__", ".git", ".pytest_cache", ".mypy_cache",
                       "node_modules", ".venv", "venv", "tmp", "dist", "build"}
#: TEMPORARY: databases / bytecode / WAL files never leave.
EXPORT_EXCLUDE_SUFFIXES = (".db", ".db-wal", ".db-shm", ".sqlite", ".sqlite3",
                           ".pyc", ".pyo", ".log")
#: TEMPORARY: scratch probe scripts must never be exported either.
EXPORT_EXCLUDE_NAMES = {"browser_probe.py", "ab_probe.py", "dbg_probe.py"}
#: TEMPORARY: single-file ceiling (200 KB).
EXPORT_MAX_FILE_BYTES = 200 * 1024
#: TEMPORARY: default characters of file content per part.
EXPORT_DEFAULT_PART_SIZE = 40000
#: TEMPORARY: hard ceiling for the ?size= query parameter.
EXPORT_MAX_PART_SIZE = 2_000_000


def export_source_files() -> list[dict]:
    """TEMPORARY: the exportable source files, as [{"path", "content"}], sorted by path.

    Sorting matters: it is what makes part N identical across calls.
    """
    collected: list[dict] = []
    for dirpath, dirnames, filenames in os.walk(PROJECT_ROOT):
        dirnames[:] = sorted(d for d in dirnames if d not in EXPORT_EXCLUDE_DIRS)
        for name in sorted(filenames):
            if name in EXPORT_EXCLUDE_NAMES:
                continue
            if name.endswith(EXPORT_EXCLUDE_SUFFIXES) or ".sqlite" in name:
                continue
            if not name.endswith(EXPORT_INCLUDE_SUFFIXES):
                continue
            full_path = os.path.join(dirpath, name)
            rel = os.path.relpath(full_path, PROJECT_ROOT).replace(os.sep, "/")
            if rel.startswith("tmp/") or "/tmp/" in rel:
                continue
            if not os.path.isfile(full_path):
                continue
            try:
                if os.path.getsize(full_path) > EXPORT_MAX_FILE_BYTES:
                    continue
                with open(full_path, "r", encoding="utf-8", errors="replace") as fh:
                    content = fh.read()
            except OSError as exc:  # pragma: no cover - unreadable file is skipped
                log.warning("export skipped %s: %s", rel, exc)
                continue
            collected.append({"path": rel, "content": content})
    collected.sort(key=lambda item: item["path"])
    return collected


def export_partition(files: list[dict], size: int) -> list[list[dict]]:
    """TEMPORARY: pack files into parts of <= `size` content characters.

    A single file is never split; a file bigger than `size` gets a part of its own.
    """
    parts: list[list[dict]] = []
    current: list[dict] = []
    current_len = 0
    for entry in files:
        length = len(entry["content"])
        if current and current_len + length > size:
            parts.append(current)
            current, current_len = [], 0
        current.append(entry)
        current_len += length
        if length > size:  # oversized single file: flush it alone
            parts.append(current)
            current, current_len = [], 0
    if current:
        parts.append(current)
    return parts


# ---------------------------------------------------------------------------
# READ-ONLY SOURCE EXPORT (/_export/*). Additive only: nothing else uses these.
# ---------------------------------------------------------------------------
#: Directories never walked into (VCS, caches, virtualenvs, deps).
_EXPORT_SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".pytest_cache",
                     ".mypy_cache", ".ruff_cache", ".venv", "venv", ".idea",
                     ".vscode", "dist", "build", ".next", ".cache"}
#: Binary / database / archive suffixes never exported.
_EXPORT_SKIP_SUFFIXES = (".pyc", ".pyo", ".pyd", ".db", ".db-wal", ".db-shm",
                         ".sqlite", ".sqlite3", ".tar.gz", ".tgz", ".zip", ".gz",
                         ".bz2", ".xz", ".7z", ".rar", ".png", ".jpg", ".jpeg",
                         ".gif", ".ico", ".webp", ".bmp", ".tif", ".tiff", ".svgz",
                         ".woff", ".woff2", ".ttf", ".otf", ".eot", ".pdf",
                         ".so", ".o", ".a", ".dll", ".dylib", ".exe", ".bin",
                         ".mp3", ".mp4", ".wav", ".ogg", ".webm", ".mov", ".avi",
                         ".log", ".pickle", ".pkl", ".npy", ".npz", ".parquet")
#: Never exported by exact name (secrets / local env).
_EXPORT_SKIP_NAMES = {".env", ".DS_Store"}


def _export_is_text(data: bytes) -> bool:
    """True when the bytes look like UTF-8 text (no NUL, decodable)."""
    if b"\x00" in data:
        return False
    try:
        data.decode("utf-8")
    except UnicodeDecodeError:
        return False
    return True


def _export_collect() -> list[dict]:
    """Every tracked text file under PROJECT_ROOT, sorted by path.

    Each entry: {"path", "bytes", "sha256", "content"}. Sorted order is what
    makes part N stable across calls.
    """
    entries: list[dict] = []
    for dirpath, dirnames, filenames in os.walk(PROJECT_ROOT):
        dirnames[:] = sorted(d for d in dirnames if d not in _EXPORT_SKIP_DIRS)
        for name in sorted(filenames):
            if name in _EXPORT_SKIP_NAMES:
                continue
            lowered = name.lower()
            if lowered.endswith(_EXPORT_SKIP_SUFFIXES):
                continue
            full_path = os.path.join(dirpath, name)
            if os.path.islink(full_path) or not os.path.isfile(full_path):
                continue
            try:
                with open(full_path, "rb") as fh:
                    data = fh.read()
            except OSError as exc:  # pragma: no cover - unreadable file skipped
                log.warning("_export skipped %s: %s", full_path, exc)
                continue
            if not _export_is_text(data):
                continue
            rel = os.path.relpath(full_path, PROJECT_ROOT).replace(os.sep, "/")
            entries.append({
                "path": rel,
                "bytes": len(data),
                "sha256": hashlib.sha256(data).hexdigest(),
                "content": data.decode("utf-8"),
            })
    entries.sort(key=lambda item: item["path"])
    return entries


def create_app(seed: bool = True) -> Flask:
    app = Flask(__name__)
    app.config["JSON_SORT_KEYS"] = False

    #: Rows come in two shapes: the older adapters return a list of cells, the
    #: keyless ones (overpass) return a dict per business. ``row_cells`` renders
    #: either into the same ordered list of display strings so one table markup
    #: serves both without a special case in the template.
    #: Column heading -> the key the keyless adapters use in a dict row.
    _ROW_KEYS = {"business": "name", "name": "name", "address": "address",
                 "lat": "lat", "lon": "lon", "category": "category",
                 "source": "source_url", "coordinates": "coords",
                 "distance": "distance_miles"}

    def _row_cells(row, columns=None):
        if isinstance(row, dict):
            keys = [str(c).strip().lower() for c in (columns or [])]
            if not keys:
                keys = ["business", "address", "lat", "lon", "category", "source"]
            out = []
            for key in keys:
                value = row.get(_ROW_KEYS.get(key, key))
                if key == "coordinates" and value is None:
                    value = f"{row.get('lat', '')}, {row.get('lon', '')}"
                out.append("" if value is None else str(value))
            return out
        return [str(cell) for cell in (row or [])]

    app.add_template_filter(_row_cells, "row_cells")

    #: Paths that always answer with JSON, never an HTML error page.
    JSON_PREFIXES = ("/jobs", "/events", "/opportunities", "/api/opportunities", "/verification", "/verify",
                     "/health", "/signals", "/api", "/audit/verify", "/audit/ledger",
                     "/audit/status", "/audit/tamper-test", "/audit/rows",
                     "/audit/trace", "/audit/_tamper", "/measurement/rules",
                     "/api/schedules", "/api/scheduler", "/api/voice", "/manifest.webmanifest",
                     "/api/avatar", "/avatar/state", "/api/live-data", "/api/heartbeat",
                     "/api/outreach", "/live-data/ingest")

    # No-cache on every response: the preview iframe must never show a stale build.
    @app.after_request
    def _no_cache(resp):
        # Chrome REFUSES to register a service worker whose script is served with
        # Cache-Control: no-store, so /sw.js gets a plain no-cache (revalidate) instead.
        # Everything else stays no-store so the preview iframe never shows a stale build.
        if request.path == "/sw.js":
            resp.headers["Cache-Control"] = "no-cache, max-age=0, must-revalidate"
            return resp
        resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
        resp.headers["Pragma"] = "no-cache"
        resp.headers["Expires"] = "0"
        return resp

    # The Command Center: an in-memory operator console layered on top of the
    # durable orchestrator. One instance per app, exposed as a JSON API and as
    # the root page. It has no spend authority and makes no network calls.
    command_center = CommandCenter()
    app.extensions["command_center"] = command_center
    app.register_blueprint(command_center_blueprint(command_center))

    register_default_components(REGISTRY)
    # The last two components, both `tool` kind (no pipeline state, never routed to):
    # the installable phone shell and the three.js front-door avatar.
    pwa.register_phone_reach(REGISTRY)
    avatar.register_avatar(REGISTRY)
    init_db()
    # The immune system's ledger: creates audit_ledger + the append-only triggers,
    # and mirrors any event rows written before this layer existed (once).
    audit.init_db()
    if seed:
        service.seed_if_empty(REGISTRY)

    # Durable memory store: its own SQLite file (data/jarvis.db).
    memory.init_db()
    if seed:
        memory.seed_if_empty()
    # The bot loop demo: specs for the opportunities that are already VERIFIED,
    # plus three SAMPLE measurements that land on KEPT / KILLED / INCONCLUSIVE.
    # Uses only opportunities that already exist; writes nothing if specs exist.
    if seed:
        try:
            measurement.seed_demo_if_empty()
        except Exception as exc:  # pragma: no cover - never block startup on the demo
            log.warning("bot demo seed skipped: %s", exc)

    # The scheduling layer's three example schedules (hourly ingest, daily
    # opportunities, daily verification). Seeded once, labelled "Seeded:" so the
    # page can say plainly which rows shipped with the app. Tick-driven only.
    if seed:
        try:
            scheduling.seed_if_empty()
        except Exception as exc:  # pragma: no cover - never block startup
            log.warning("schedule seed skipped: %s", exc)

    # -- live data: the eight real adapters, seeded with the 2026-11-18 captures --
    try:
        live_data.seed_if_empty()
    except Exception as exc:  # pragma: no cover - never block startup
        log.warning("live data seed skipped: %s", exc)

    # -- outreach: the lead store lives in the memory DB, seeded once --
    try:
        outreach.init_db()
        if seed:
            outreach.seed_if_empty()
    except Exception as exc:  # pragma: no cover - never block startup
        log.warning("outreach seed skipped: %s", exc)

    # -- source snapshot: the whole project as one .tar.gz, built in memory only --
    @app.get("/snapshot.tar.gz")
    def snapshot_targz():
        """Stream the project source as a gzipped tar, assembled entirely in RAM.

        Included: *.py, *.html, *.txt, *.md and .gitignore.
        Excluded: databases/WAL, caches, bytecode, VCS metadata, logs, .env.
        Nothing is ever written to disk.
        """
        buf = io.BytesIO()
        packed: list[str] = []
        with tarfile.open(fileobj=buf, mode="w:gz") as tar:
            for dirpath, dirnames, filenames in os.walk(PROJECT_ROOT):
                dirnames[:] = sorted(d for d in dirnames if d not in SNAPSHOT_EXCLUDE_DIRS)
                for name in sorted(filenames):
                    if name in SNAPSHOT_EXCLUDE_NAMES or name.endswith(SNAPSHOT_EXCLUDE_SUFFIXES):
                        continue
                    if name not in SNAPSHOT_INCLUDE_NAMES and not name.endswith(SNAPSHOT_INCLUDE_SUFFIXES):
                        continue
                    full_path = os.path.join(dirpath, name)
                    if not os.path.isfile(full_path):
                        continue
                    tar.add(full_path, arcname=os.path.relpath(full_path, PROJECT_ROOT), recursive=False)
                    packed.append(os.path.relpath(full_path, PROJECT_ROOT))
        data = buf.getvalue()
        log.info("source snapshot: %d files, %d bytes", len(packed), len(data))
        return Response(
            data,
            mimetype="application/gzip",
            headers={
                "Content-Disposition": "attachment; filename=jarvis-source.tar.gz",
                "Content-Length": str(len(data)),
            },
        )

    # ------------------------------------------------------------------
    # TEMPORARY: chunked source export, so the tree can be copied out of
    # the sandbox over plain HTTP. REMOVE THESE TWO ROUTES AFTER THE EXPORT.
    # ------------------------------------------------------------------
    @app.get("/export/manifest")
    def export_manifest():
        """TEMPORARY: part count + file inventory, no content."""
        raw_size = request.args.get("size", str(EXPORT_DEFAULT_PART_SIZE))
        try:
            size = int(raw_size)
        except (TypeError, ValueError):
            return jsonify({"error": "bad_request", "message": "size must be an integer"}), 400
        if size < 1 or size > EXPORT_MAX_PART_SIZE:
            return jsonify({"error": "bad_request",
                            "message": f"size must be between 1 and {EXPORT_MAX_PART_SIZE}"}), 400
        files = export_source_files()
        parts = export_partition(files, size)
        payload = {
            "total_parts": len(parts),
            "file_count": len(files),
            "total_bytes": sum(len(entry["content"]) for entry in files),
            "files": [entry["path"] for entry in files],
        }
        return Response(json.dumps(payload, ensure_ascii=False), mimetype="application/json")

    @app.get("/export/source")
    def export_source():
        """TEMPORARY: GET /export/source?part=N&size=40000 -> one slice of the source."""
        raw_part = request.args.get("part", "1")
        raw_size = request.args.get("size", str(EXPORT_DEFAULT_PART_SIZE))
        try:
            part_no = int(raw_part)
            size = int(raw_size)
        except (TypeError, ValueError):
            return jsonify({"error": "bad_request",
                            "message": "part and size must be integers"}), 400
        if size < 1 or size > EXPORT_MAX_PART_SIZE:
            return jsonify({"error": "bad_request",
                            "message": f"size must be between 1 and {EXPORT_MAX_PART_SIZE}"}), 400
        files = export_source_files()
        parts = export_partition(files, size)
        total = len(parts)
        if part_no < 1 or part_no > total:
            return jsonify({"error": "not_found",
                            "message": f"part {part_no} out of range 1..{total}",
                            "part": part_no, "total_parts": total}), 404
        payload = {"part": part_no, "total_parts": total, "files": parts[part_no - 1]}
        log.info("TEMPORARY export: part %d/%d, %d files", part_no, total, len(parts[part_no - 1]))
        return Response(json.dumps(payload, ensure_ascii=False), mimetype="application/json")

    # ------------------------------------------------------------------
    # READ-ONLY SOURCE EXPORT: /_export/manifest.
    # Purely additive: no existing route or behaviour is touched.
    # ------------------------------------------------------------------
    @app.get("/_export/manifest")
    def _export_manifest():
        """Inventory of every tracked text file: path, byte size, sha256."""
        entries = _export_collect()
        payload = {
            "total_files": len(entries),
            "total_bytes": sum(e["bytes"] for e in entries),
            "files": [{"path": e["path"], "bytes": e["bytes"], "sha256": e["sha256"]}
                      for e in entries],
        }
        return Response(json.dumps(payload, ensure_ascii=False), mimetype="application/json")

    # -- error handling: always clean JSON for /api and /jobs, HTML elsewhere --
    @app.errorhandler(OrchestratorError)
    def _handle_orch_error(exc: OrchestratorError):
        payload = {"error": exc.code, "message": str(exc)}
        if getattr(exc, "allowed", None) is not None:
            payload["allowed_transitions"] = exc.allowed
        if isinstance(exc, (VerificationBlocked, BotBuildBlocked, MeasurementBlocked)):
            payload["verdict"] = exc.verdict
            payload["details"] = exc.details
        if request.path.startswith(JSON_PREFIXES):
            return jsonify(payload), exc.status
        return render_template("error.html", error=payload, status=exc.status), exc.status

    @app.errorhandler(404)
    def _handle_404(exc):
        if request.path.startswith(("/jobs", "/events", "/health", "/verification", "/verify",
                                    "/api", "/audit/verify", "/audit/ledger", "/audit/status",
                                    "/audit/tamper-test", "/audit/rows", "/audit/trace",
                                    "/audit/_tamper")):
            return jsonify({"error": "not_found", "message": f"no route {request.path}"}), 404
        return render_template(
            "error.html", error={"error": "not_found", "message": f"no route {request.path}"}, status=404
        ), 404

    # ---------------------------- health ---------------------------------
    @app.get("/health")
    def health():
        body = service.health()
        body["signals"] = ingestion.signal_counts()
        body["ingestion"] = {"component": "IngestionLayer", "real_fetch": True,
                             "sources": [s["name"] for s in ingestion.source_describe()]}
        body["opportunities"] = opportunity.counts()
        audit_state = audit.verify()
        body["audit"] = {
            "component": audit.COMPONENT_NAME,
            "table": audit.LEDGER,
            "append_only": True,
            "triggers": ["audit_ledger_no_update", "audit_ledger_no_delete"],
            "ok": audit_state["ok"],
            "length": audit_state["length"],
            "first_broken_seq": audit_state["first_broken_seq"],
            "algorithm": audit.HASH_ALGORITHM,
        }
        body["bot_factory"] = {
            "component": bot_factory.COMPONENT_NAME,
            "spec_version": bot_factory.SPEC_VERSION,
            "counts": bot_factory.counts(),
            "model_calls": 0,
            "deployed": False,
        }
        body["measurement"] = {
            "component": measurement.COMPONENT_NAME,
            "rule_version": measurement.RULE_VERSION,
            "counts": measurement.counts(),
        }
        body["verification"] = {
            "component": verification.COMPONENT_NAME,
            "rule_version": verification.RULE_VERSION,
            "counts": verification.verdict_counts(),
            "real_fetch": True,
        }
        return jsonify(body)

    # ---------------------------- jobs -----------------------------------
    @app.post("/jobs")
    def create_job():
        body = request.get_json(silent=True)
        if body is None:
            body = request.form.to_dict() or {}
        if not isinstance(body, dict):
            raise ValidationError("request body must be a JSON object")
        payload = body.get("payload", {})
        if isinstance(payload, str):
            import json as _json

            try:
                payload = _json.loads(payload) if payload.strip() else {}
            except ValueError as exc:
                raise ValidationError(f"payload is not valid JSON: {exc}") from exc
        job = service.create_job(
            title=body.get("title", ""),
            source=body.get("source", ""),
            payload=payload or {},
            registry=REGISTRY,
        )
        return jsonify(job), 201

    @app.get("/jobs")
    def list_jobs():
        state = request.args.get("state")
        limit = request.args.get("limit", type=int) or 500
        jobs = service.list_jobs(state=state, limit=limit)
        return jsonify({"jobs": jobs, "count": len(jobs), "state_filter": state})

    @app.get("/jobs/<job_id>")
    def get_job(job_id):
        return jsonify(service.get_job(job_id))

    @app.post("/jobs/<job_id>/advance")
    def advance_job(job_id):
        result = service.advance(job_id, registry=REGISTRY)
        return jsonify(result)

    @app.post("/jobs/<job_id>/reject")
    def reject_job(job_id):
        body = request.get_json(silent=True) or request.form.to_dict() or {}
        result = service.reject(job_id, reason=body.get("reason", ""), actor=body.get("actor", "operator"))
        return jsonify(result)

    # ---------------------------- events ---------------------------------
    @app.get("/events")
    def events():
        limit = request.args.get("limit", type=int) or 100
        job_id = request.args.get("job_id")
        kind = request.args.get("kind")
        rows = service.list_events(limit=limit, job_id=job_id, kind=kind)
        return jsonify({"events": rows, "count": len(rows), "chain": service.chain_status()})

    @app.get("/events/verify")
    def events_verify():
        return jsonify(service.chain_status())

    # ---------------------------- senses / ingestion ----------------------
    @app.get("/senses")
    def senses():
        run = None
        run_id = request.args.get("run", type=int)
        if run_id:
            run = ingestion.get_run(run_id)
        if run is None:
            recent = ingestion.list_runs(limit=1)
            run = recent[0] if recent else None
        return render_template(
            "senses.html",
            grouped=ingestion.grouped_signals(),
            counts=ingestion.signal_counts(),
            runs=ingestion.list_runs(limit=8),
            run=run,
            sources=ingestion.source_describe(),
            chain=service.chain_status(),
        )

    @app.post("/ingest")
    def ingest():
        """Trigger a REAL fetch of every configured source. No keys, no fakes."""
        body = request.get_json(silent=True) or {}
        limit = body.get("limit") or request.args.get("limit", type=int) or 15
        try:
            limit = max(1, min(int(limit), 50))
        except (TypeError, ValueError):
            raise ValidationError("limit must be an integer")
        run = ingestion.run_ingest(limit_per_source=limit, trigger="api")
        return jsonify(run)

    @app.get("/signals")
    def signals():
        source = request.args.get("source")
        limit = request.args.get("limit", type=int) or 200
        rows = ingestion.list_signals(source=source, limit=limit)
        return jsonify(
            {
                "signals": rows,
                "count": len(rows),
                "source_filter": source,
                "counts": ingestion.signal_counts(),
                "sources": ingestion.source_describe(),
            }
        )

    @app.get("/ingest/runs")
    def ingest_runs():
        limit = request.args.get("limit", type=int) or 20
        runs = ingestion.list_runs(limit=limit)
        return jsonify({"runs": runs, "count": len(runs)})

    @app.post("/ui/senses/fetch")
    def ui_senses_fetch():
        try:
            run = ingestion.run_ingest(trigger="ui")
            return redirect(url_for("senses", run=run["id"]))
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui fetch failed: %s", exc)
            return redirect(url_for("senses"))


    # ---------------------------- opportunities --------------------------
    @app.get("/api/opportunities")
    def opportunities():
        """JSON listing. The HTML page lives at GET /opportunities (see below)."""
        status = request.args.get("status")
        limit = request.args.get("limit", type=int) or 200
        rows = opportunity.list_opportunities(status=status, limit=limit)
        return jsonify(
            {
                "opportunities": rows,
                "count": len(rows),
                "status_filter": status,
                "counts": opportunity.counts(),
                "rules_version": opportunity.RULES["version"],
            }
        )

    @app.get("/opportunities/rules")
    def opportunities_rules():
        """The explicit, inspectable scoring rules. No black box."""
        return jsonify(opportunity.rules_document())

    @app.get("/opportunities/rejections")
    def opportunities_rejections():
        limit = request.args.get("limit", type=int) or 50
        rows = opportunity.list_rejections(limit=limit)
        return jsonify({"rejections": rows, "count": len(rows)})

    @app.get("/opportunities/runs")
    def opportunities_runs():
        limit = request.args.get("limit", type=int) or 20
        rows = opportunity.list_runs(limit=limit)
        return jsonify({"runs": rows, "count": len(rows)})

    @app.get("/api/opportunities/<opp_id>")
    def opportunity_detail(opp_id):
        opp = opportunity.get_opportunity(opp_id)
        if opp is None:
            raise ValidationError(f"no opportunity with id {opp_id!r}")
        return jsonify(opp)

    @app.post("/opportunities/run")
    def opportunities_run():
        body = request.get_json(silent=True) or {}
        limit = body.get("limit") or request.args.get("limit", type=int) or 500
        try:
            limit = max(1, min(int(limit), 2000))
        except (TypeError, ValueError):
            raise ValidationError("limit must be an integer")
        run = opportunity.run_engine(limit=limit, actor="api")
        run.pop("opportunities", None)
        return jsonify(run)

    @app.post("/opportunities/<opp_id>/queue")
    def opportunity_queue(opp_id):
        if opportunity.get_opportunity(opp_id) is None:
            raise ValidationError(f"no opportunity with id {opp_id!r}")
        result = opportunity.opportunity_to_job(opp_id, registry=REGISTRY)
        return jsonify(result), (201 if result["created"] else 200)

    # ---------------------------- verification ---------------------------
    @app.get("/verification")
    def verification_runs_api():
        limit = request.args.get("limit", type=int) or 20
        opp_id = request.args.get("opportunity")
        rows = verification.list_runs(limit=limit, opportunity_id=opp_id)
        return jsonify(
            {
                "runs": rows,
                "count": len(rows),
                "counts": verification.verdict_counts(),
                "rule_version": verification.RULE_VERSION,
            }
        )

    @app.get("/verification/rules")
    def verification_rules():
        return jsonify(verification.rules_document())

    @app.get("/verification/counts")
    def verification_counts():
        return jsonify(verification.verdict_counts())

    @app.get("/verification/runs/<int:run_id>")
    def verification_run_detail(run_id):
        run = verification.get_run(run_id)
        if run is None:
            raise ValidationError(f"no verification run with id {run_id}")
        return jsonify(run)

    @app.post("/opportunities/<opp_id>/verify")
    def verify_opportunity_api(opp_id):
        """Re-fetch every cited source for one opportunity and return the verdict.

        A successful run returns 200 even when the verdict is UNVERIFIED or
        CONTRADICTED: the verification worked, the answer is simply negative.
        """
        if opportunity.get_opportunity(opp_id) is None:
            raise ValidationError(f"no opportunity with id {opp_id!r}")
        body = request.get_json(silent=True) or {}
        trigger = str(body.get("trigger") or request.args.get("trigger") or "api")
        run = verification.verify_opportunity(opp_id, trigger=trigger)
        return jsonify(run)

    @app.post("/verification/run-all")
    def verify_all_api():
        body = request.get_json(silent=True) or {}
        opp_ids = body.get("opportunity_ids")
        if opp_ids is not None and not isinstance(opp_ids, list):
            raise ValidationError("opportunity_ids must be a list of opportunity ids")
        sweep = verification.verify_all(opp_ids, trigger="api-all")
        return jsonify(sweep)

    # ---------------------------- registry -------------------------------
    @app.get("/components")
    def components():
        return jsonify({"components": REGISTRY.describe(), "states": sm.ALL_STATES})

    @app.get("/states")
    def states():
        return jsonify(
            {
                "pipeline": sm.PIPELINE_STATES,
                "terminal": sm.TERMINAL_STATES,
                "transitions": sm.TRANSITIONS,
            }
        )

    # ---------------------------- memory store ---------------------------
    # Durable, citation-enforced record. JSON only, writes validated in
    # orchestrator.memory (a claim without source_url + source_turn is refused).
    def _payload() -> dict:
        body = request.get_json(silent=True)
        if body is None:
            body = request.form.to_dict() or {}
        if not isinstance(body, dict):
            raise ValidationError("request body must be a JSON object")
        return body

    @app.get("/api/memory/opportunities")
    def api_memory_opportunities():
        status = request.args.get("status")
        limit = request.args.get("limit", type=int) or 200
        rows = memory.list_opportunities(status=status, limit=limit)
        return jsonify(
            {
                "opportunities": rows,
                "count": len(rows),
                "status_filter": status,
                "stats": memory.stats(),
            }
        )

    @app.post("/api/memory/opportunities")
    def api_memory_create_opportunity():
        body = _payload()
        row = memory.create_opportunity(
            title=body.get("title", ""),
            source_url=body.get("source_url", ""),
            found_at=body.get("found_at"),
            status=body.get("status", "open"),
            opp_id=body.get("id"),
        )
        return jsonify(row), 201

    @app.get("/api/memory/claims")
    def api_memory_claims():
        opp_id = request.args.get("opportunity") or request.args.get("opportunity_id")
        limit = request.args.get("limit", type=int) or 200
        rows = memory.list_claims(opportunity_id=opp_id, limit=limit)
        return jsonify(
            {
                "claims": rows,
                "count": len(rows),
                "opportunity_filter": opp_id,
                "citation_rule": "source_url AND source_turn are required on every claim",
            }
        )

    @app.post("/api/memory/claims")
    def api_memory_create_claim():
        """No citation, no claim: 400 citation_required, nothing written."""
        body = _payload()
        row = memory.create_claim(
            opportunity_id=body.get("opportunity_id", ""),
            text=body.get("text", ""),
            source_url=body.get("source_url"),
            source_turn=body.get("source_turn"),
            captured_at=body.get("captured_at"),
        )
        return jsonify(row), 201

    @app.get("/api/memory/decisions")
    def api_memory_decisions():
        opp_id = request.args.get("opportunity") or request.args.get("opportunity_id")
        limit = request.args.get("limit", type=int) or 200
        rows = memory.list_decisions(opportunity_id=opp_id, limit=limit)
        return jsonify({"decisions": rows, "count": len(rows), "opportunity_filter": opp_id})

    @app.post("/api/memory/decisions")
    def api_memory_create_decision():
        body = _payload()
        row = memory.create_decision(
            opportunity_id=body.get("opportunity_id", ""),
            verdict=body.get("verdict", ""),
            rule_version=body.get("rule_version", ""),
            rationale=body.get("rationale", ""),
            decided_at=body.get("decided_at"),
        )
        return jsonify(row), 201

    @app.get("/api/memory/outcomes")
    def api_memory_outcomes():
        opp_id = request.args.get("opportunity") or request.args.get("opportunity_id")
        limit = request.args.get("limit", type=int) or 200
        rows = memory.list_outcomes(opportunity_id=opp_id, limit=limit)
        return jsonify({"outcomes": rows, "count": len(rows), "opportunity_filter": opp_id})

    @app.post("/api/memory/outcomes")
    def api_memory_create_outcome():
        body = _payload()
        row = memory.create_outcome(
            opportunity_id=body.get("opportunity_id", ""),
            metric=body.get("metric", ""),
            value=body.get("value"),
            measured_at=body.get("measured_at"),
        )
        return jsonify(row), 201

    @app.get("/api/memory/rules")
    def api_memory_rules():
        rows = memory.list_rules()
        return jsonify(
            {
                "rules": rows,
                "count": len(rows),
                "latest": rows[0]["version"] if rows else None,
            }
        )

    @app.post("/api/memory/rules")
    def api_memory_create_rule():
        body = _payload()
        row = memory.create_rule(
            version=body.get("version", ""),
            description=body.get("description", ""),
            precision=body.get("precision"),
            recall=body.get("recall"),
            published_at=body.get("published_at"),
        )
        return jsonify(row), 201

    @app.get("/api/memory/search")
    def api_memory_search():
        q = request.args.get("q", "")
        limit = request.args.get("limit", type=int) or 100
        result = memory.search(q, limit=limit)
        result["stats"] = memory.stats()
        return jsonify(result)

    @app.get("/api/memory/stats")
    def api_memory_stats():
        return jsonify(memory.stats())

    @app.get("/memory")
    def memory_page():
        return render_template(
            "memory.html",
            stats=memory.stats(),
            opportunities=memory.list_opportunities(),
            decisions=memory.latest_decisions(),
            rules=memory.list_rules(),
            claims=memory.list_claims(limit=200),
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
            opportunity_counts=opportunity.counts(),
        )

    # ---------------------------- bot factory ----------------------------
    # Deterministic specs for VERIFIED opportunities. Nothing here is deployed:
    # a spec is a document, and every page says so.

    @app.get("/api/bots")
    def api_bots():
        status = request.args.get("status")
        rows = bot_factory.list_specs(status=status, limit=500)
        return jsonify(
            {
                "bots": rows,
                "count": len(rows),
                "counts": bot_factory.counts(),
                "model": bot_factory.rules_document(),
                "honesty": bot_factory.HONESTY,
                "deployed": False,
            }
        )

    @app.get("/api/bots/<int:bot_id>")
    def api_bot_detail(bot_id):
        bot = bot_factory.get_spec(bot_id)
        if bot is None:
            raise JobNotFound(f"no bot spec with id {bot_id}")
        bot["measurements"] = measurement.list_measurements(bot_id)
        bot["decisions"] = measurement.list_decisions(bot_id)
        return jsonify(bot)

    @app.post("/api/bots/build")
    def api_bots_build():
        body = _payload()
        opp_id = str(body.get("opportunity_id") or body.get("opportunity") or "").strip()
        if not opp_id:
            raise ValidationError("opportunity_id is required")
        force = str(body.get("force", "")).lower() in ("1", "true", "yes", "on")
        result = bot_factory.build_bot(
            opp_id,
            trigger=str(body.get("trigger") or "api"),
            job_id=body.get("job_id") or None,
            force=force,
        )
        payload = {
            "bot": result["bot"],
            "spec": result["spec"],
            "created": result["created"],
            "reused": result["reused"],
            "deployed": False,
            "honesty": bot_factory.HONESTY,
        }
        return jsonify(payload), (201 if result["created"] else 200)

    @app.get("/bots")
    def bots_page():
        rows = measurement.list_bots()
        return render_template(
            "bots.html",
            bots=rows,
            counts=bot_factory.counts(),
            measurement_counts=measurement.counts(),
            model=bot_factory.rules_document(),
            opportunities=opportunity.list_opportunities(),
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
        )

    @app.get("/bots/<int:bot_id>")
    def bot_detail_page(bot_id):
        bot = measurement.get_bot(bot_id)
        if bot is None:
            raise JobNotFound(f"no bot spec with id {bot_id}")
        return render_template(
            "bot_detail.html",
            bot=bot,
            model=bot_factory.rules_document(),
            rule=measurement.active_rule(),
            job=_safe_job_for_page(bot.get("job_id")),
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
        )

    @app.post("/ui/bots/build")
    def ui_bots_build():
        opp_id = request.form.get("opportunity_id", "").strip()
        try:
            result = bot_factory.build_bot(opp_id, trigger="ui")
            return redirect(url_for("bot_detail_page", bot_id=result["bot"]["id"]))
        except (BotBuildBlocked, ValidationError) as exc:
            log.warning("ui bot build refused for %s: %s", opp_id, exc)
            return redirect(url_for("ui_opportunities", build_error=str(exc)))

    @app.post("/ui/bots/<int:bot_id>/measure")
    def ui_bots_measure(bot_id):
        form = request.form.to_dict()
        try:
            measurement.record_measurement(
                bot_id,
                runs=form.get("runs"),
                successes=form.get("successes"),
                failures=form.get("failures") or None,
                revenue_usd=form.get("revenue_usd") or 0,
                cost_usd=form.get("cost_usd") or 0,
                notes=form.get("notes", ""),
            )
        except OrchestratorError as exc:
            log.warning("ui measurement refused for bot %s: %s", bot_id, exc)
        return redirect(url_for("measurement_page", bot=bot_id))

    def _safe_job_for_page(job_id):
        if not job_id:
            return None
        try:
            return service.get_job(job_id)
        except OrchestratorError:
            return None

    # ---------------------------- measurement / keep-or-kill --------------
    @app.get("/measurement")
    def measurement_page():
        rows = measurement.list_bots()
        focus = request.args.get("bot", type=int)
        return render_template(
            "measurement.html",
            bots=rows,
            counts=measurement.counts(),
            bot_counts=bot_factory.counts(),
            rule=measurement.active_rule(),
            rules=measurement.rules_document(),
            decisions=measurement.all_decisions(limit=25),
            focus=focus,
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
        )

    @app.get("/measurement/rules")
    def measurement_rules():
        return jsonify(measurement.rules_document())

    @app.get("/api/measurement")
    def api_measurement():
        rows = measurement.list_bots()
        return jsonify(
            {
                "bots": rows,
                "count": len(rows),
                "counts": measurement.counts(),
                "rule": measurement.active_rule(),
                "thresholds": measurement.THRESHOLDS,
                "rule_version": measurement.RULE_VERSION,
                "honesty": measurement.HONESTY,
            }
        )

    @app.get("/api/measurement/<int:bot_id>")
    def api_measurement_bot(bot_id):
        bot = measurement.get_bot(bot_id)
        if bot is None:
            raise JobNotFound(f"no bot spec with id {bot_id}")
        return jsonify(bot)

    @app.post("/api/measurement/record")
    def api_measurement_record():
        body = _payload()
        bot_id = body.get("bot_id")
        if bot_id in (None, ""):
            raise ValidationError("bot_id is required")
        try:
            bot_id = int(bot_id)
        except (TypeError, ValueError):
            raise ValidationError("bot_id must be an integer")
        result = measurement.record_measurement(
            bot_id,
            runs=body.get("runs"),
            successes=body.get("successes"),
            failures=body.get("failures") if body.get("failures") not in ("", None) else None,
            revenue_usd=body.get("revenue_usd") or 0,
            cost_usd=body.get("cost_usd") or 0,
            notes=str(body.get("notes", "")),
            sample=str(body.get("sample", "")).lower() in ("1", "true", "yes", "on"),
        )
        return jsonify(result), 201

    # ---------------------------- audit (immune system) ------------------
    # Append-only, hash-chained ledger. Every component writes through
    # orchestrator.audit.record(); SQLite triggers forbid UPDATE and DELETE.

    @app.get("/audit/verify")
    def audit_verify_api():
        """Walk the whole chain.

        Contract: {ok: true, length: N} on success; {ok: false, broken_at: <row
        id>, reason: "..."} naming the EXACT row where the chain stops making
        sense (mutated content, deleted row, reordered row). Nothing is cached
        and nothing is repaired — every call recomputes from genesis.
        """
        return jsonify(audit.status())

    @app.get("/audit/rows")
    def audit_rows_api():
        limit = request.args.get("limit", type=int) or 100
        rows = audit.recent(
            limit=limit,
            actor=request.args.get("component") or None,
            action=request.args.get("event_type") or None,
            subject=request.args.get("subject") or None,
        )
        return jsonify({"rows": rows, "count": len(rows), "verify": audit.verify(),
                        "facets": audit.facets()})

    @app.get("/audit/trace/<path:subject>")
    def audit_trace_api(subject):
        """Every event touching one subject (job id / opportunity id / run id)."""
        return jsonify(audit.trace(subject))

    # ---- DEV-ONLY: tamper injection, so the demo can prove the verifier works.
    # There is no way to show a verifier catching tampering on a table that
    # cannot be tampered with, so this pair of routes deliberately corrupts (and
    # then restores) ONE REAL ledger row. Underscore-prefixed, dev-guarded
    # (JARVIS_ALLOW_TAMPER=0 disables both), never called by any component.
    @app.post("/audit/_tamper")
    def audit_dev_tamper_api():
        if not audit.dev_tamper_enabled():
            return jsonify(audit.dev_tamper(0))  # returns the disabled notice
        body = request.get_json(silent=True) or request.form.to_dict() or {}
        row_id = body.get("row_id") or body.get("id")
        field = body.get("field") or "payload_json"
        if row_id in (None, ""):
            # no row given: pick the middle of the chain so there is a tail behind it
            rows = audit.recent(limit=1000)
            if not rows:
                return jsonify({"ok": False, "applied": False, "dev_only": True,
                                "error": "the ledger is empty; nothing to tamper with"}), 400
            seqs = sorted(r["seq"] for r in rows)
            row_id = seqs[len(seqs) // 2]
        result = audit.dev_tamper(row_id, field=field, value=body.get("value"))
        return jsonify(result), (200 if result.get("applied") else 400)

    @app.post("/audit/_tamper/restore")
    def audit_dev_restore_api():
        return jsonify(audit.dev_restore())

    @app.get("/audit/_tamper/state")
    def audit_dev_state_api():
        state = audit.dev_state()
        state["verify"] = audit.verify()
        return jsonify(state)

    @app.get("/audit/ledger")
    def audit_ledger_api():
        limit = request.args.get("limit", type=int) or 100
        rows = audit.recent(limit=limit)
        return jsonify(
            {
                "table": audit.LEDGER,
                "append_only": True,
                "triggers": ["audit_ledger_no_update", "audit_ledger_no_delete"],
                "algorithm": audit.HASH_ALGORITHM,
                "genesis_prev_hash": "0" * 64,
                "rows": rows,
                "count": len(rows),
                "verify": audit.verify(),
                "counts": audit.counts(),
            }
        )

    @app.get("/audit/status")
    def audit_status_api():
        state = audit.verify()
        counts = audit.counts()
        tip = audit.head()
        return jsonify(
            {
                "ok": state["ok"],
                "status": "CHAIN INTACT" if state["ok"] else "CHAIN BROKEN",
                "length": state["length"],
                "broken_at": state["broken_at"],
                "reason": state["reason"],
                "first_broken_seq": state["first_broken_seq"],
                "detail": state["detail"],
                "head_hash": state["head_hash"],
                "head": tip,
                "checked_at": state["checked_at"],
                "dev_tamper": audit.dev_state(),
                "actors": counts["actors"],
            }
        )

    @app.post("/audit/tamper-test")
    def audit_tamper_test_api():
        """Real tamper test: blocked UPDATE/DELETE + corrupted scratch copy."""
        return jsonify(audit.tamper_test())

    @app.get("/audit")
    def audit_page():
        limit = request.args.get("limit", type=int) or 100
        component = request.args.get("component") or None
        event_type = request.args.get("event_type") or None
        subject = request.args.get("subject") or None
        state = audit.verify()
        return render_template(
            "audit.html",
            state=state,
            head=audit.head(),
            rows=audit.recent(limit=limit, actor=component, action=event_type,
                              subject=subject),
            facets=audit.facets(),
            component=component,
            event_type=event_type,
            trace=audit.trace(subject) if subject else None,
            dev_state=audit.dev_state(),
            counts=audit.counts(),
            limit=limit,
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
        )

    # ---------------------------- scheduling layer -----------------------
    # Tick-driven, NOT a daemon. Every route below performs its work because a
    # request asked for it; nothing fires on its own in this sandbox. Each run is
    # written through orchestrator.audit.record() inside orchestrator.scheduling.

    @app.get("/schedules")
    def schedules_page():
        """The Schedules page. Its JSON listing is GET /api/schedules."""
        return render_template(
            "schedules.html",
            schedules=scheduling.list_schedules(),
            describe=scheduling.describe(),
            last_tick=scheduling.last_tick(),
            cadences=scheduling.CADENCES,
            target_kinds=scheduling.TARGET_KINDS,
            target_descriptions=scheduling.TARGET_DESCRIPTIONS,
            weekdays=scheduling.WEEKDAY_LABELS,
            timezone=scheduling.TIMEZONE,
            honesty=scheduling.HONESTY,
            loop=scheduler_loop.status(),
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
        )

    @app.get("/api/schedules")
    def api_schedules():
        rows = scheduling.list_schedules()
        return jsonify(
            {
                "schedules": rows,
                "count": len(rows),
                "enabled": sum(1 for s in rows if s["enabled"]),
                "due_now": sum(1 for s in rows if s["enabled"] and s["due"]),
                "last_tick": scheduling.last_tick(),
                "timezone": scheduling.TIMEZONE,
                "cadences": list(scheduling.CADENCES),
                "target_kinds": list(scheduling.TARGET_KINDS),
                "tick_driven": True,
                "background_daemon": False,
                "honesty": scheduling.HONESTY,
                "loop": scheduler_loop.status(),
            }
        )

    @app.post("/api/schedules")
    def api_schedules_create():
        body = _payload()
        row = scheduling.create_schedule(
            str(body.get("name") or ""),
            str(body.get("target_kind") or ""),
            target_id=body.get("target_id") or None,
            cadence=str(body.get("cadence") or scheduling.CADENCE_DAILY),
            at_minute=body.get("at_minute", 0),
            at_hour=body.get("at_hour", 9),
            days_of_week=body.get("days_of_week", ""),
            enabled=str(body.get("enabled", "true")).lower() in ("1", "true", "yes", "on"),
        )
        return jsonify({"schedule": row, "tick_driven": True,
                        "background_daemon": False}), 201

    @app.post("/api/schedules/<int:schedule_id>/toggle")
    def api_schedules_toggle(schedule_id):
        body = _payload()
        enabled = body.get("enabled")
        if enabled is not None:
            enabled = str(enabled).lower() in ("1", "true", "yes", "on")
        row = scheduling.toggle_schedule(schedule_id, enabled)
        return jsonify({"schedule": row, "enabled": row["enabled"]})

    @app.post("/api/schedules/<int:schedule_id>/run-now")
    def api_schedules_run_now(schedule_id):
        result = scheduling.run_now(schedule_id)
        return jsonify(result)

    @app.post("/api/scheduler/tick")
    def api_scheduler_tick():
        """Run exactly ONE tick. Returns what fired, what was skipped, and why."""
        result = scheduling.tick()
        result["honesty"] = scheduling.HONESTY
        return jsonify(result)

    @app.get("/api/scheduler")
    def api_scheduler_status():
        payload = scheduling.describe()
        payload["loop"] = scheduler_loop.status()
        return jsonify(payload)

    # -- the in-process background loop: status + manual run ----------------
    @app.get("/api/scheduler/loop")
    def api_scheduler_loop():
        return jsonify(scheduler_loop.status())

    @app.post("/api/scheduler/loop/run")
    def api_scheduler_loop_run():
        """Run one cycle NOW, on demand. Same code path the timer thread uses."""
        state = scheduler_loop.run_once(trigger="manual")
        return jsonify({"loop": scheduler_loop.status(), "state": state})

    @app.post("/ui/scheduler/loop/run")
    def ui_scheduler_loop_run():
        try:
            scheduler_loop.run_once(trigger="manual")
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("manual scheduler loop run failed: %s", exc)
        return redirect(url_for("schedules_page"))

    @app.post("/ui/schedules")
    def ui_schedules_create():
        form = request.form.to_dict()
        try:
            scheduling.create_schedule(
                form.get("name", ""),
                form.get("target_kind", ""),
                cadence=form.get("cadence") or scheduling.CADENCE_DAILY,
                at_minute=form.get("at_minute") or 0,
                at_hour=form.get("at_hour") or 9,
                days_of_week=form.get("days_of_week", ""),
            )
        except OrchestratorError as exc:
            log.warning("ui schedule create refused: %s", exc)
        return redirect(url_for("schedules_page"))

    @app.post("/ui/schedules/<int:schedule_id>/toggle")
    def ui_schedules_toggle(schedule_id):
        try:
            scheduling.toggle_schedule(schedule_id)
        except OrchestratorError as exc:
            log.warning("ui schedule toggle refused: %s", exc)
        return redirect(url_for("schedules_page"))

    @app.post("/ui/schedules/<int:schedule_id>/run-now")
    def ui_schedules_run_now(schedule_id):
        try:
            scheduling.run_now(schedule_id)
        except OrchestratorError as exc:
            log.warning("ui schedule run-now refused: %s", exc)
        return redirect(url_for("schedules_page"))

    @app.post("/ui/scheduler/tick")
    def ui_scheduler_tick():
        try:
            scheduling.tick()
        except OrchestratorError as exc:
            log.warning("ui scheduler tick failed: %s", exc)
        return redirect(url_for("schedules_page"))

    # ---------------------------- local voice ----------------------------
    # The audio never reaches this server: the browser's Web Speech API does the
    # recognition and the synthesis. Only the transcript is POSTed here, and every
    # command is written to the audit ledger with its resolved intent.

    @app.get("/voice")
    def voice_page():
        return render_template(
            "voice.html",
            commands=voice.commands_document(),
            intents=list(voice.INTENTS),
            honesty=voice.HONESTY,
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
            recent=audit.recent(limit=12, actor=voice.COMPONENT_NAME),
        )


    # ---------------------------- phone reach (PWA) ----------------------
    # The control panel is installable: a manifest, a versioned service worker,
    # generated icons and one mobile home screen. This is a PWA over HTTPS, NOT
    # telephony — there is no number, no SMS and no call anywhere in this build.

    @app.get("/manifest.webmanifest")
    def manifest_webmanifest():
        return Response(pwa.manifest_json(), mimetype="application/manifest+json")

    @app.get("/sw.js")
    def service_worker():
        resp = Response(pwa.service_worker_js(), mimetype="application/javascript")
        # the worker must be allowed to control the whole origin, not just /sw.js
        resp.headers["Service-Worker-Allowed"] = "/"
        return resp

    @app.get("/phone")
    def phone_page():
        ran = (request.args.get("ran") or "").strip().lower()
        failed = bool(request.args.get("err"))
        return render_template(
            "phone.html",
            snapshot=pwa.loop_snapshot(),
            buildable=pwa.buildable_opportunities(),
            pwa=pwa.describe(),
            honesty=pwa.HONESTY,
            cache_version=pwa.CACHE_VERSION,
            actions=pwa.PHONE_ACTIONS,
            action_labels=pwa.ACTION_LABELS,
            chain=service.chain_status(),
            ran=pwa.ACTION_LABELS.get(ran, ran) if ran else None,
            ran_message=request.args.get("msg", ""),
            ran_seq=request.args.get("seq", type=int),
            ran_ok=not failed,
            recent_actions=audit.recent(limit=6, actor=pwa.COMPONENT_NAME),
        )

    @app.post("/phone/action")
    def phone_action():
        """Run one phone action through the EXISTING layer, then audit the origin."""
        action = (request.form.get("action") or "").strip().lower()
        opportunity_id = (request.form.get("opportunity_id") or "").strip() or None
        try:
            result = pwa.run_action(action, opportunity_id=opportunity_id)
        except OrchestratorError as exc:
            log.warning("phone action %s refused: %s", action, exc)
            return redirect(url_for("phone_page", ran=action or "action", msg=str(exc), err=1))
        return redirect(url_for(
            "phone_page", ran=result["action"], msg=result["message"], seq=result["audit_seq"]
        ))

    @app.get("/api/phone")
    def api_phone():
        return jsonify({
            "component": pwa.COMPONENT_NAME,
            "manifest": pwa.MANIFEST_URL,
            "service_worker": pwa.SW_URL,
            "cache_version": pwa.CACHE_VERSION,
            "actions": pwa.describe()["actions"],
            "real_telephony": False,
            "phone_number": None,
            "sms": False,
            "calls": False,
            "honesty": pwa.HONESTY,
            "snapshot": pwa.loop_snapshot(),
        })

    # ---------------------------- 3D avatar (front door) -----------------
    # A browser-rendered three.js head. The states are driven by real speech /
    # command events; the face visualises no cognition and is not sentient.

    @app.get("/avatar")
    def avatar_page():
        return render_template(
            "avatar.html",
            three_version=avatar.THREE_VERSION,
            three_cdn=avatar.THREE_CDN,
            three_fallback_cdn=avatar.THREE_FALLBACK_CDN,
            component=avatar.COMPONENT_NAME,
            states=list(avatar.STATES),
            state_meaning=dict(avatar.STATE_MEANING),
            honesty=avatar.HONESTY,
            description=avatar.describe(),
            recent=avatar.recent_states(limit=6),
            chain=service.chain_status(),
        )

    @app.get("/api/avatar")
    def api_avatar():
        body = avatar.describe()
        body["recent"] = avatar.recent_states(limit=10)
        return jsonify(body)

    @app.post("/avatar/state")
    def avatar_state():
        """Record a state the visitor actually caused (IDLE/LISTENING/THINKING/SPEAKING)."""
        body = _payload()
        state = body.get("state")
        row = avatar.record_state(
            state,
            source=str(body.get("source") or "avatar-ui"),
            detail=str(body.get("detail") or ""),
        )
        return jsonify(row)

    @app.get("/api/voice/commands")
    def api_voice_commands():
        return jsonify(voice.commands_document())

    @app.post("/api/voice/command")
    def api_voice_command():
        body = _payload()
        transcript = body.get("transcript")
        if transcript is None:
            transcript = body.get("text") or body.get("query") or ""
        result = voice.handle_command(
            transcript, source=str(body.get("source") or "browser")
        )
        return jsonify(result)

    # ---------------------------- dashboard ------------------------------
    def _pipeline_context() -> dict:
        counts = service.counts_by_state()
        jobs = service.list_jobs()
        events = service.list_events(limit=40)
        chain = service.chain_status()
        pipeline = [
            {
                "state": s,
                "label": sm.STATE_LABELS[s],
                "count": counts.get(s, 0),
                "next": sm.next_state(s),
            }
            for s in sm.PIPELINE_STATES
        ]
        return {
            "pipeline": pipeline,
            "jobs": jobs,
            "events": events,
            "counts": counts,
            "chain": chain,
            "terminal_states": [s for s in sm.ALL_STATES if s not in sm.PIPELINE_STATES],
            "components": REGISTRY.describe(),
            "total_jobs": len(jobs),
            "signal_counts": ingestion.signal_counts(),
            "opportunity_counts": opportunity.counts(),
        }

    @app.get("/")
    def dashboard():
        """The Command Center. The raw orchestrator view lives at /pipeline."""
        context = _pipeline_context()
        context["initial_state"] = command_center.snapshot()
        return render_template("command.html", **context)

    @app.get("/pipeline")
    def pipeline_page():
        """The original orchestrator view: raw jobs, events, components."""
        return render_template("dashboard.html", **_pipeline_context())


    @app.get("/opportunities")
    def opportunities_page():
        """The Opportunities page. Its JSON listing is GET /api/opportunities."""
        return ui_opportunities()

    @app.get("/ui/opportunities")
    def ui_opportunities():
        run_id = request.args.get("run", type=int)
        run = None
        if run_id:
            run = next((r for r in opportunity.list_runs(limit=50) if r["id"] == run_id), None)
        if run is None:
            recent = opportunity.list_runs(limit=1)
            run = recent[0] if recent else None
        return render_template(
            "opportunities.html",
            opportunities=opportunity.list_opportunities(),
            counts=opportunity.counts(),
            run=run,
            rejections=opportunity.list_rejections(limit=20),
            rules=opportunity.rules_document(),
            signal_counts=ingestion.signal_counts(),
            chain=service.chain_status(),
            build_error=request.args.get("build_error"),
        )

    @app.post("/ui/opportunities/run")
    def ui_opportunities_run():
        try:
            run = opportunity.run_engine(actor="ui")
            return redirect(url_for("ui_opportunities", run=run["id"]))
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui opportunity run failed: %s", exc)
            return redirect(url_for("ui_opportunities"))

    @app.post("/ui/opportunities/<opp_id>/queue")
    def ui_opportunity_queue(opp_id):
        try:
            opportunity.opportunity_to_job(opp_id, registry=REGISTRY)
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui queue failed for %s: %s", opp_id, exc)
        return redirect(url_for("ui_opportunities"))

    @app.get("/ui/verification")
    def ui_verification():
        runs = verification.list_runs(limit=25)
        run_id = request.args.get("run", type=int)
        run = None
        if run_id:
            run = next((r for r in runs if r["id"] == run_id), None)
            if run is None:
                run = verification.get_run(run_id)
        if run is None:
            recent = verification.list_runs(limit=1)
            run = recent[0] if recent else None
        return render_template(
            "verification.html",
            opportunities=verification.decorate_opportunities(
                opportunity.list_opportunities()
            ),
            counts=verification.verdict_counts(),
            opportunity_counts=opportunity.counts(),
            runs=runs,
            run=run,
            rules=verification.rules_document(),
            rule_version=verification.RULE_VERSION,
            chain=service.chain_status(),
            signal_counts=ingestion.signal_counts(),
        )

    @app.post("/ui/verification/run-all")
    def ui_verification_run_all():
        try:
            sweep = verification.verify_all(trigger="ui-all")
            first = sweep["runs"][0]["id"] if sweep["runs"] else None
            return redirect(url_for("ui_verification", run=first))
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui verify-all failed: %s", exc)
            return redirect(url_for("ui_verification"))

    @app.post("/ui/verification/<opp_id>/verify")
    def ui_verification_run_one(opp_id):
        if opportunity.get_opportunity(opp_id) is None:
            raise ValidationError(f"no opportunity with id {opp_id!r}")
        try:
            run = verification.verify_opportunity(opp_id, trigger="ui")
            return redirect(url_for("ui_verification", run=run["id"]))
        except VerificationBlocked:
            raise
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui verify failed for %s: %s", opp_id, exc)
            return redirect(url_for("ui_verification"))

    @app.get("/ui/jobs/<job_id>")
    def ui_job_detail(job_id):
        job = service.get_job(job_id)
        return render_template(
            "job.html",
            job=job,
            chain=service.chain_status(),
            components=REGISTRY.describe(),
        )

    @app.post("/ui/jobs")
    def ui_create_job():
        title = request.form.get("title", "").strip()
        source = request.form.get("source", "").strip() or "ui/manual"
        if not title:
            return redirect(url_for("dashboard"))
        service.create_job(title=title, source=source, payload={"note": "created from dashboard"}, registry=REGISTRY)
        return redirect(url_for("dashboard"))

    @app.post("/ui/jobs/<job_id>/advance")
    def ui_advance(job_id):
        try:
            service.advance(job_id, registry=REGISTRY)
        except OrchestratorError as exc:
            log.warning("ui advance failed for %s: %s", job_id, exc)
        return redirect(url_for("dashboard"))

    @app.post("/ui/jobs/<job_id>/reject")
    def ui_reject(job_id):
        try:
            service.reject(job_id, reason="rejected from dashboard")
        except OrchestratorError as exc:
            log.warning("ui reject failed for %s: %s", job_id, exc)
        return redirect(url_for("dashboard"))

    # =====================================================================
    # LIVE DATA — eight real adapters, honest status, capture log
    # =====================================================================
    @app.get("/live-data")
    def live_data_page():
        # The scheduler is in-process: make sure it is alive whenever anyone looks.
        heartbeat.ensure_started()
        snap = live_data.snapshot()
        mapbox_card = next((c for c in snap["sources"] if c["id"] == "mapbox"), None)
        return render_template(
            "live_data.html",
            snapshot=snap,
            ingest=live_ingest.last_ingest(),
            loop=scheduler_loop.status(),
            chain=service.chain_status(),
            # The Secrets strip: NAMES + PRESENT/MISSING only. No value, no slice
            # of a value, ever reaches this template.
            secrets=secrets_vault.summary(),
            mapbox={
                "source_id": "mapbox",
                "status": (mapbox_card or {}).get("status", "NEEDS KEY"),
                "detail": (mapbox_card or {}).get("detail", ""),
                "signals": len((mapbox_card or {}).get("signals") or []),
                "count": len((mapbox_card or {}).get("rows") or []),
                "category": mapbox_source.DEFAULT_CATEGORY,
                "categories": list(mapbox_source.CATEGORIES),
                "market": (mapbox_card or {}).get("market") or None,
                "radius_miles": mapbox_source.DEFAULT_RADIUS_MILES,
                "label": mapbox_source.DEFAULT_LABEL,
                "lat": mapbox_source.DEFAULT_LAT,
                "lon": mapbox_source.DEFAULT_LON,
                "scope": mapbox_source.scope_line(),
                "credential": secrets_vault.status().get("MAPBOX_TOKEN", "MISSING"),
                "mode": "6 categories · Search Box forward query · 25 per category",
            },
        )

    @app.get("/api/live-data")
    def api_live_data():
        """The registry as JSON, one row per source with its evidence.

        ``?probe=1`` makes the request do the real work first: it probes every
        source that has never been checked (the same sweep the startup warm
        runs), so a reader who wants a guarantee about *now* can ask for one
        instead of trusting a capture timestamp. With no parameter it is a pure
        read of the most recent recorded results.
        """
        if request.args.get("probe") in ("1", "true", "yes"):
            live_data.probe_never_probed()
        return jsonify(live_data.snapshot())

    @app.get("/api/secrets")
    def api_secrets():
        """Which credentials are present. Names and PRESENT/MISSING only.

        There is deliberately no route that returns a value: the vault's ``get()``
        is not reachable over HTTP at all.
        """
        return jsonify(secrets_vault.summary())

    @app.get("/secrets/status")
    def secrets_status():
        """``{name, configured: true|false}`` for every known key. Read-only.

        The smallest possible disclosure: a name and a boolean per key, plus
        counts. No value, no slice of a value, no length, no prefix — the vault's
        ``get()`` is never called from any request handler, so a value cannot
        reach a response body by accident. There is no POST/PUT/DELETE here
        either: keys are set out-of-band (environment or the 0600 vault file).
        """
        rows = secrets_api.status_rows()
        return jsonify({
            "keys": rows,
            "configured": sum(1 for r in rows if r["configured"]),
            "missing": sum(1 for r in rows if not r["configured"]),
            "total": len(rows),
            "read_only": True,
            "vault": secrets_api.path_display(),
        })

    @app.post("/live-data/ingest")
    def live_data_ingest():
        """THE BRIDGE: live signals -> cited opportunity claims.

        One route, one job. It calls the ingest bridge with a fresh operational
        connection and returns the per-source summary as JSON:
        ``{source_id: {status, signals, claims_written, ...}}``. A source that
        refused us (401/402/403) comes back ``DEGRADED`` with its literal reason
        and zero claims — the route never invents one to fill the shape.
        """
        conn = db_connect()
        try:
            summary = live_ingest.ingest_live_signals(conn)
        finally:
            conn.close()
        return jsonify(summary)

    @app.post("/api/live-data/test")
    def api_live_data_test():
        """Re-run every adapter for real. Failures are recorded as failures."""
        run = live_data.probe_all(trigger="api")
        return jsonify(run)

    @app.post("/api/live-data/test/<source_id>")
    def api_live_data_test_one(source_id):
        """Re-run ONE adapter for real and record it.

        Same contract as the whole-registry route, scoped to a single source so a
        slow adapter (the Overpass mirror failover can take a minute) never blocks
        a check of a fast one. An unknown id is a 404, not an empty pass.
        """
        source = live_data.SOURCE_BY_ID.get(source_id)
        if source is None:
            return jsonify({"error": f"unknown source id: {source_id}",
                            "known": sorted(live_data.SOURCE_BY_ID)}), 404
        entry = live_data._probe_one(source)
        live_data._record_capture(entry)
        try:
            audit.record(
                actor=live_data.COMPONENT_NAME,
                action="live_data.probe",
                subject_type="source",
                subject_id=entry["source_id"],
                payload={"status": entry["status"], "http_code": entry["http_code"],
                         "detail": entry["detail"], "source_url": entry["source_url"],
                         "rows": len(entry["rows"]),
                         "result_count": entry.get("result_count"),
                         "trigger": "api:one"},
            )
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("audit write failed for probe %s: %s", source_id, exc)
        return jsonify(entry)

    @app.post("/ui/live-data/test")
    def ui_live_data_test():
        try:
            live_data.probe_all(trigger="ui")
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui live-data probe failed: %s", exc)
        return redirect(url_for("live_data_page"))

    # =====================================================================
    # HEARTBEAT — the real in-process scheduler
    # =====================================================================
    @app.get("/api/heartbeat")
    def api_heartbeat():
        heartbeat.ensure_started()
        return jsonify(heartbeat.status())

    @app.post("/api/heartbeat/jobs/<job_id>/run")
    def api_heartbeat_run(job_id):
        if job_id not in heartbeat.JOB_BY_ID:
            raise ValidationError(f"no job with id {job_id!r}")
        return jsonify(heartbeat.run_job(job_id, trigger="api"))

    @app.post("/ui/heartbeat/jobs/<job_id>/run")
    def ui_heartbeat_run(job_id):
        if job_id not in heartbeat.JOB_BY_ID:
            raise ValidationError(f"no job with id {job_id!r}")
        try:
            heartbeat.run_job(job_id, trigger="ui")
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("ui job run failed for %s: %s", job_id, exc)
        return redirect(url_for("live_data_page"))

    # =====================================================================
    # OUTREACH — draft only. There is no send route, by construction.
    # =====================================================================
    @app.get("/outreach")
    def outreach_page():
        return render_template(
            "outreach.html",
            snapshot=outreach.snapshot(),
            chain=service.chain_status(),
        )

    @app.get("/api/outreach")
    def api_outreach():
        return jsonify(outreach.snapshot())

    @app.post("/api/outreach/leads/<int:lead_id>/draft")
    def api_outreach_draft(lead_id):
        return jsonify(outreach.create_draft(lead_id))

    @app.post("/api/outreach/drafts/<int:draft_id>/approve")
    def api_outreach_approve(draft_id):
        body = request.get_json(silent=True) or {}
        return jsonify(outreach.approve_draft(draft_id, approved_by=body.get("approved_by") or "operator"))

    @app.post("/api/outreach/bots/<int:bot_id>/draft/<int:lead_id>")
    def api_outreach_bot_draft(bot_id, lead_id):
        return jsonify(outreach.create_draft_from_bot(bot_id, lead_id))

    @app.post("/ui/outreach/bots/<int:bot_id>/draft/<int:lead_id>")
    def ui_outreach_bot_draft(bot_id, lead_id):
        try:
            outreach.create_draft_from_bot(bot_id, lead_id)
        except OrchestratorError as exc:
            log.warning("ui bot draft failed for bot %s lead %s: %s", bot_id, lead_id, exc)
        return redirect(url_for("outreach_page"))

    @app.post("/ui/outreach/leads/<int:lead_id>/draft")
    def ui_outreach_draft(lead_id):
        try:
            outreach.create_draft(lead_id)
        except OrchestratorError as exc:
            log.warning("ui draft failed for lead %s: %s", lead_id, exc)
        return redirect(url_for("outreach_page"))

    @app.post("/ui/outreach/drafts/<int:draft_id>/approve")
    def ui_outreach_approve(draft_id):
        try:
            outreach.approve_draft(draft_id, approved_by="operator")
        except OrchestratorError as exc:
            log.warning("ui approve failed for draft %s: %s", draft_id, exc)
        return redirect(url_for("outreach_page"))

    return app


app = create_app()


# --- L1: auto-install the audit decorator over every mutating route ---
# Appended Nov 22, 2026. Wraps each mutating view once, after all routes exist.
# Idempotent: a second run is a no-op. Marker: _install_audit_gate
def _install_audit_gate(app):
    from orchestrator.audit import audited

    MUTATING = {"POST", "PUT", "PATCH", "DELETE"}
    wrapped = 0

    for rule in app.url_map.iter_rules():
        if rule.endpoint == "static":
            continue
        if not (rule.methods & MUTATING):
            continue
        view = app.view_functions.get(rule.endpoint)
        if view is None or getattr(view, "_audited_action", None):
            continue
        app.view_functions[rule.endpoint] = audited("route." + rule.endpoint)(view)
        wrapped += 1

    print(f"[audit-gate] wrapped {wrapped} mutating routes")


_install_audit_gate(app)


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "3000"))
    # -- live data: check, for real, every source that has no capture yet -----
    # Runs on a daemon thread so the port opens immediately. This is what makes a
    # freshly restarted process show a truthful LIVE badge for the Tavily adapter
    # without anyone pressing a button: the badge is still the outcome of a real,
    # authenticated HTTP call, recorded with its own timestamp.
    try:
        live_data.seed_if_empty()
        live_data.warm_in_background()
    except Exception as exc:  # pragma: no cover - never block startup
        log.warning("live data first-probe warm skipped: %s", exc)

    # The heartbeat is a real background thread inside this process. It dies with
    # the process; a supervisor (systemd/launchd) is what makes it survive restarts.
    if os.environ.get("JARVIS_HEARTBEAT", "1") != "0":
        heartbeat.start()
    # The in-process scheduler loop: a daemon thread in THIS process that calls
    # scheduling.tick() every few hours. Not an OS supervisor — see
    # orchestrator/scheduler_loop.py and the Schedules page.
    if os.environ.get("JARVIS_SCHEDULER_LOOP", "1") != "0":
        scheduler_loop.start()
    log.info("JARVIS Orchestrator listening on http://0.0.0.0:%d", port)
    app.run(host="0.0.0.0", port=port, debug=False, threaded=True)
