"""orchestrator/runner.py — execute a stored bot spec.

Walks a spec's steps, dispatches each action to a registered handler,
threads one store dict through the run, runs the spec's own verifier
checks, records a measurement, and writes a bot.run ledger row.

CLI:  python3 -m orchestrator.runner <bot_id>
"""

from __future__ import annotations

import logging
import sys
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timezone
from typing import Any, Callable

from orchestrator import audit, bot_factory, measurement

log = logging.getLogger(__name__)


class RunBlocked(Exception):
    """Raised when a spec cannot run."""


# ---------------------------------------------------------------- handlers

def _fetch_feed(url: str) -> list[dict]:
    """Minimal RSS reader. Returns [] on anything unexpected."""
    req = urllib.request.Request(
        url, headers={"User-Agent": "jarvis-runner/1.0 (local orchestrator)"}
    )
    with urllib.request.urlopen(req, timeout=20) as resp:
        raw = resp.read()
    try:
        root = ET.fromstring(raw)
    except ET.ParseError:
        return []
    out = []
    for item in root.iter("item"):
        title = (item.findtext("title") or "").strip()
        link = (item.findtext("link") or "").strip()
        pub = (item.findtext("pubDate") or "").strip()
        if title and link:
            out.append({"title": title, "url": link, "published_at": pub})
    return out


def _read_feeds(step, store, spec):
    """Bind feeds and fetch articles.

    The spec's `inputs` block declares a schema (feed_ids: array[string]) — it
    is not bound values. Nothing else supplies them, so the runner does it here.
    Override with JARVIS_FEEDS=a,b,c in the environment.
    """
    import os

    try:
        from . import feeds as _feeds
    except ImportError:
        import feeds as _feeds

    inputs = spec.get("inputs") or {}
    env_feeds = [f.strip() for f in (os.environ.get("JARVIS_FEEDS") or "").split(",") if f.strip()]
    feed_ids = env_feeds or spec.get("feed_ids") or inputs.get("feed_ids") or []
    if not isinstance(feed_ids, list):
        feed_ids = []
    window_days = spec.get("window_days") or 7

    articles = _feeds.fetch_articles(feed_ids or None, window_days=window_days)
    store["articles"] = articles
    return articles


def _extract_claims(step: dict, store: dict, ctx: dict) -> dict:
    """STRUCTURAL — headline is the claim, URL is the source. No model call."""
    claims = []
    for art in store.get("articles") or []:
        title = (art.get("title") or "").strip()
        url = (art.get("url") or "").strip()
        if not title or not url:
            continue
        claims.append({
            "claim": title,
            "source_url": url,
            "published_at": art.get("published_at") or "",
        })
    store["claims"] = claims
    return {"claims": len(claims)}


def _drop_uncited(step: dict, store: dict, ctx: dict) -> dict:
    kept, dropped = [], 0
    for c in store.get("claims") or []:
        url = (c.get("source_url") or "").strip()
        if url.startswith("http://") or url.startswith("https://"):
            kept.append(c)
        else:
            dropped += 1
    store["claims_cited"] = kept
    store["dropped_uncited"] = dropped
    return {"kept": len(kept), "dropped": dropped}


def _draft_brief(step: dict, store: dict, ctx: dict) -> dict:
    claims = store.get("claims_cited") or []
    name = ctx.get("bot_name") or "brief"
    lines = [f"# {name}", ""]
    if not claims:
        lines.append("_No cited claims this run._")
    for c in claims:
        lines.append(f"- {c['claim']} — {c['source_url']}")
    lines.append("")
    lines.append(f"_Dropped uncited: {store.get('dropped_uncited', 0)}_")
    store["brief_markdown"] = "\n".join(lines)
    return {"brief_markdown": len(store["brief_markdown"])}


def _notify_owner(step: dict, store: dict, ctx: dict) -> dict:
    """Queue for human approval. Never sends."""
    store["approval_queue"] = [{
        "bot_name": ctx.get("bot_name"),
        "brief_markdown": store.get("brief_markdown", ""),
        "queued_at": datetime.now(timezone.utc).isoformat(),
        "requires_human": True,
    }]
    store["send_requires_human"] = True
    return {"queued": 1}


HANDLERS: dict[str, Callable[[dict, dict, dict], dict]] = {
    "read_feeds": _read_feeds,
    "extract_claims": _extract_claims,
    "drop_uncited": _drop_uncited,
    "draft_brief": _draft_brief,
    "notify_owner": _notify_owner,
}


# ---------------------------------------------------------------- verifier

def _check_outputs_present(spec: dict, store: dict) -> tuple[bool, str]:
    fields = ((spec.get("outputs") or {}).get("fields")) or {}
    missing = [f for f in fields if f not in store]
    if missing:
        return False, f"missing outputs: {', '.join(missing)}"
    return True, "all declared outputs present"


def _check_no_silent_green(spec: dict, store: dict) -> tuple[bool, str]:
    steps = spec.get("steps") or []
    if not steps:
        return False, "spec has no steps"
    ran = store.get("_steps_ran") or []
    if len(ran) < len(steps):
        return False, f"only {len(ran)}/{len(steps)} steps ran"
    if not store.get("brief_markdown"):
        return False, "no brief produced — green exit with no work"
    return True, f"{len(ran)} steps ran, brief produced"


def _check_citations_resolve(spec: dict, store: dict) -> tuple[bool, str]:
    claims = store.get("claims_cited") or []
    if not claims:
        return False, "no cited claims to resolve"
    bad = [c for c in claims if not str(c.get("source_url", "")).startswith("http")]
    if bad:
        return False, f"{len(bad)} claims without a resolvable URL"
    return True, f"{len(claims)} citations resolve"


CHECKS: dict[str, Callable[[dict, dict], tuple[bool, str]]] = {
    "outputs_present": _check_outputs_present,
    "no_silent_green": _check_no_silent_green,
    "citations_resolve": _check_citations_resolve,
}


# ---------------------------------------------------------------- run_spec

def _tier_gate(action, ctx):
    """Classify one bot step before it runs. Never raises - returns a verdict.

    A bot run has no human present, so a Tier 2 action cannot be granted. The
    run stops and reports instead of crashing, which is the difference between
    a blocked step and a broken bot.
    """
    from . import tiers

    tier = tiers.classify(action)
    value = int(getattr(tier, "value", -1))
    label = getattr(tier, "name", str(tier))
    basis = ""
    explain = getattr(tiers, "explain", None)
    if callable(explain):
        try:
            basis = " " + str(explain(action))
        except Exception:
            basis = ""

    record = {"action": action, "tier": value, "label": label}
    ctx.setdefault("_tiers", []).append(record)

    if value >= 3:
        record["allowed"] = False
        record["reason"] = (
            "%s is Tier 3 FORBIDDEN (%s). No grant unlocks this - the run "
            "stopped rather than pretending the step did not happen.%s"
            % (action, label, basis)
        )
        return record

    if value == 2:
        record["allowed"] = False
        record["reason"] = (
            "%s is Tier 2 APPROVE (%s) and no human is present in an automated "
            "run, so it cannot be granted. The bot cannot work to its full "
            "potential until this is granted or the step is reclassified.%s"
            % (action, label, basis)
        )
        return record

    record["allowed"] = True
    record["reason"] = "%s is Tier %d %s.%s" % (action, value, label, basis)
    return record


def run_spec(bot_id: int, *, dry_run: bool = False) -> dict:
    row = bot_factory.get_spec(bot_id)
    if not row:
        raise RunBlocked(f"no spec with id {bot_id}")

    spec = row.get("spec") or {}
    bot_name = row.get("bot_name") or spec.get("bot_name") or f"bot-{bot_id}"

    store: dict[str, Any] = {"_steps_ran": []}
    ctx = {
        "bot_name": bot_name,
        "bot_id": bot_id,
        "feeds": (spec.get("inputs") or {}).get("feeds") or [],
    }

    errors: list[str] = []
    blocked: list[dict[str, Any]] = []
    for step in spec.get("steps") or []:
        action = step.get("action")
        handler = HANDLERS.get(action)

        # Safety Protocol Article 1: classify BEFORE the action runs.
        _verdict = _tier_gate(action, ctx)
        if not _verdict["allowed"]:
            blocked.append(_verdict)
            errors.append("BLOCKED " + _verdict["reason"])
            log.warning("blocked step: %s", action)
            break

        if handler is None:
            errors.append(f"unimplemented action: {action}")
            continue
        try:
            handler(step, store, ctx)
            store["_steps_ran"].append(action)
        except Exception as exc:
            errors.append(f"{action}: {exc}")
            log.exception("step failed: %s", action)

    checks = []
    for check in ((spec.get("verifier") or {}).get("checks") or []):
        cid = check.get("id")
        fn = CHECKS.get(cid)
        if fn is None:
            checks.append({"id": cid, "ok": False, "note": "unimplemented check"})
            continue
        try:
            ok, note = fn(spec, store)
        except Exception as exc:
            ok, note = False, f"check raised: {exc}"
        checks.append({"id": cid, "ok": ok, "note": note})

    verified = bool(checks) and all(c["ok"] for c in checks) and not errors

    result = {
        "bot_id": bot_id,
        "bot_name": bot_name,
        "verified": verified,
        "checks": checks,
        "errors": errors,
        "outputs": {k: v for k, v in store.items() if not k.startswith("_")},
    }

    if dry_run:
        return result

    try:
        measurement.record_measurement(
            bot_id,
            runs=1,
            successes=1 if verified else 0,
            failures=0 if verified else 1,
            notes=f"run_spec verified={verified}",
        )
    except Exception as exc:
        log.exception("measurement failed")
        result["errors"].append(f"measurement: {exc}")

    try:
        audit.record("runner", "bot.run", "bot_spec", str(bot_id), {
            "bot_id": bot_id,
            "bot_name": bot_name,
            "verified": verified,
            "checks": checks,
            "errors": errors,
        })
    except Exception as exc:
        log.exception("ledger write failed")
        result["errors"].append(f"ledger: {exc}")

    return result


def main(argv: list[str] | None = None) -> int:
    argv = argv if argv is not None else sys.argv[1:]
    if not argv:
        print("usage: python3 -m orchestrator.runner <bot_id> [--dry-run]")
        return 2
    dry = "--dry-run" in argv
    bot_id = int([a for a in argv if not a.startswith("--")][0])
    try:
        result = run_spec(bot_id, dry_run=dry)
    except RunBlocked as exc:
        print(f"BLOCKED: {exc}")
        return 1
    print(f"bot: {result['bot_name']}  verified: {result['verified']}")
    for c in result["checks"]:
        print(f"  [{'ok' if c['ok'] else 'FAIL'}] {c['id']}: {c['note']}")
    for e in result["errors"]:
        print(f"  error: {e}")
    return 0 if result["verified"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
