"""Service layer: intake, routing, advance, reject, queries.

This is the only module that writes to the DB. Every write happens inside one
transaction that also appends the matching audit event(s), so the job row and
the log can never disagree.
"""

from __future__ import annotations

import json
import logging
import uuid
from datetime import datetime, timezone

from . import audit
from . import state_machine as sm
from . import verification
from .db import CURRENT_CONN, LOCK, connect, init_db
from .errors import IllegalTransition, JobNotFound, ValidationError
from .events import append_event, row_to_event, utcnow, verify_chain
from .registry import REGISTRY, Registry

log = logging.getLogger("jarvis.service")


# --- helpers --------------------------------------------------------------

def _row_to_job(row) -> dict:
    job = dict(row)
    try:
        job["payload"] = json.loads(job.get("payload") or "{}")
    except (ValueError, TypeError):
        job["payload"] = {}
    job["is_seed"] = bool(job.get("is_seed"))
    return job


def _age_seconds(created_at: str) -> int:
    try:
        dt = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
    except ValueError:
        return 0
    return max(0, int((datetime.now(timezone.utc) - dt).total_seconds()))


def human_age(seconds: int) -> str:
    if seconds < 60:
        return f"{seconds}s"
    if seconds < 3600:
        return f"{seconds // 60}m"
    if seconds < 86400:
        return f"{seconds // 3600}h"
    return f"{seconds // 86400}d"


def _fetch_job(conn, job_id: str) -> dict:
    row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
    if row is None:
        raise JobNotFound(f"no job with id {job_id!r}")
    return _row_to_job(row)


def _set_state(conn, job_id: str, state: str, payload: dict) -> None:
    conn.execute(
        "UPDATE jobs SET state = ?, payload = ?, updated_at = ? WHERE id = ?",
        (state, json.dumps(payload, sort_keys=True), utcnow(), job_id),
    )


# --- intake ---------------------------------------------------------------

def create_job(
    title: str,
    source: str,
    payload: dict | None = None,
    *,
    is_seed: bool = False,
    registry: Registry | None = None,
) -> dict:
    """Create a job, run the intake component, and log both facts."""
    registry = registry or REGISTRY
    title = (title or "").strip()
    source = (source or "").strip()
    if not title:
        raise ValidationError("title is required and must be a non-empty string")
    if not source:
        raise ValidationError("source is required and must be a non-empty string")
    if payload is None:
        payload = {}
    if not isinstance(payload, dict):
        raise ValidationError("payload must be a JSON object")

    init_db()
    job_id = uuid.uuid4().hex
    now = utcnow()

    with LOCK:
        conn = connect()
        try:
            conn.execute(
                """INSERT INTO jobs (id, title, source, payload, state, is_seed, created_at, updated_at)
                   VALUES (?,?,?,?,?,?,?,?)""",
                (job_id, title, source, json.dumps(payload, sort_keys=True),
                 sm.INGESTED, 1 if is_seed else 0, now, now),
            )
            # ONE write path: the audit layer appends the ledger row AND projects
            # the legacy job-centric event, on this same connection, atomically.
            audit.record(
                "Orchestrator", "job.created", "job", job_id,
                {"title": title, "source": source, "is_seed": is_seed,
                 "state": sm.INGESTED, "payload": payload},
                conn=conn,
                legacy={
                    "job_id": job_id,
                    "kind": "job_created",
                    "from_state": None,
                    "to_state": sm.INGESTED,
                    "note": f"job created from source={source!r}"
                            + (" (seed data)" if is_seed else ""),
                    "data": {"title": title, "source": source, "is_seed": is_seed},
                },
            )

            # Route intake through the registry rather than hard-coding it.
            intake = registry.get_intake(sm.INGESTED)
            job = _fetch_job(conn, job_id)
            if intake is not None:
                # Let the component write inside THIS transaction (no nested lock).
                token = CURRENT_CONN.set(conn)
                try:
                    result = intake.handler(job)
                finally:
                    CURRENT_CONN.reset(token)
                patch = result.get("payload_patch") or {}
                merged = {**job["payload"], **patch}
                to_state = result.get("to_state", sm.INGESTED)
                # Intake is not a transition: it enriches the job at INGESTED.
                # Any other target must still be a legal edge from INGESTED.
                if to_state != sm.INGESTED:
                    sm.assert_transition(sm.INGESTED, to_state)
                _set_state(conn, job_id, to_state, merged)
                audit.record(
                    intake.name, "component.invoked", "job", job_id,
                    {"from": sm.INGESTED, "to": to_state, "note": result.get("note", ""),
                     "data": result.get("data")},
                    conn=conn,
                    legacy={
                        "job_id": job_id,
                        "kind": "component_invoked",
                        "from_state": sm.INGESTED,
                        "to_state": to_state,
                        "note": result.get("note", ""),
                        "data": result.get("data"),
                    },
                )
            conn.commit()
            return _fetch_job(conn, job_id)
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()


# --- routing / advance ----------------------------------------------------

def advance(job_id: str, registry: Registry | None = None) -> dict:
    """Route the job to the component that handles its current state."""
    registry = registry or REGISTRY
    init_db()
    with LOCK:
        conn = connect()
        try:
            job = _fetch_job(conn, job_id)
            from_state = job["state"]

            if sm.is_terminal(from_state):
                raise IllegalTransition(
                    f"job {job_id} is in terminal state {from_state}; it cannot advance",
                    allowed=[],
                )

            component = registry.get_for_state(from_state)  # raises NoComponent
            log.info("routing job=%s state=%s -> component=%s", job_id, from_state, component.name)

            token = CURRENT_CONN.set(conn)
            try:
                result = component.handler(job) or {}
            finally:
                CURRENT_CONN.reset(token)
            to_state = result.get("to_state")
            if not to_state:
                raise IllegalTransition(
                    f"component {component.name} returned no to_state for job {job_id}",
                    allowed=sm.allowed_from(from_state),
                )
            sm.assert_transition(from_state, to_state)

            # THE IMMUNE-SYSTEM GATE, second enforcement point. The verifier
            # already refuses to return VERIFIED for an unverified claim; this
            # check runs at the transition boundary as well, inside the same
            # transaction, so a replaced or buggy component still cannot advance
            # an opportunity whose stored verdict is not VERIFIED.
            if to_state in (sm.VERIFIED, sm.BOT_BUILT):
                facts = verification.facts_for_job(job, conn)
                sm.assert_verification_gate(
                    from_state,
                    to_state,
                    cites_signals=facts["cites_signals"],
                    verdict=facts["verdict"],
                    rule_version=facts["rule_version"],
                    citations=facts["citations"],
                    blocking_signal_ids=facts["blocking"] or None,
                    opportunity_id=facts["opportunity_id"],
                    job_id=job_id,
                )

            # THE BOT-FACTORY GATE, second enforcement point. The factory already
            # refuses to build for an opportunity that is not VERIFIED; this runs at
            # the transition boundary too (inside the same transaction) so a replaced
            # or buggy component cannot build a spec from an unverified opportunity.
            if to_state == sm.BOT_BUILT:
                facts = verification.facts_for_job(job, conn)
                sm.assert_bot_build_gate(
                    from_state,
                    to_state,
                    verdict=facts["verdict"],
                    opportunity_id=facts["opportunity_id"],
                    job_id=job_id,
                )

            patch = result.get("payload_patch") or {}
            merged = {**job["payload"], **patch}
            _set_state(conn, job_id, to_state, merged)
            audit_row = audit.record(
                component.name, "state.transition", "job", job_id,
                {"from": from_state, "to": to_state, "component": component.name,
                 "note": result.get("note", ""), "data": result.get("data")},
                conn=conn,
                legacy={
                    "job_id": job_id,
                    "kind": "component_invoked",
                    "from_state": from_state,
                    "to_state": to_state,
                    "note": result.get("note", ""),
                    "data": result.get("data"),
                },
            )
            event = audit_row["legacy_event"]
            conn.commit()
            updated = _fetch_job(conn, job_id)
            return {
                "job": updated,
                "transition": {"from": from_state, "to": to_state},
                "component": component.name,
                "event": event,
            }
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()


def reject(job_id: str, reason: str = "", actor: str = "operator") -> dict:
    """Terminal REJECTED transition, available from any non-terminal state."""
    init_db()
    reason = (reason or "").strip()
    with LOCK:
        conn = connect()
        try:
            job = _fetch_job(conn, job_id)
            from_state = job["state"]
            sm.assert_transition(from_state, sm.REJECTED)
            _set_state(conn, job_id, sm.REJECTED, job["payload"])
            note = f"rejected by {actor}" + (f": {reason}" if reason else " (no reason given)")
            audit_row = audit.record(
                actor, "state.transition.rejected", "job", job_id,
                {"from": from_state, "to": sm.REJECTED, "reason": reason,
                 "note": note},
                conn=conn,
                legacy={
                    "job_id": job_id,
                    "kind": "state_transition",
                    "from_state": from_state,
                    "to_state": sm.REJECTED,
                    "note": note,
                    "data": {"reason": reason},
                },
            )
            event = audit_row["legacy_event"]
            conn.commit()
            return {"job": _fetch_job(conn, job_id), "event": event}
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()


# --- queries --------------------------------------------------------------

def list_jobs(state: str | None = None, limit: int = 500) -> list[dict]:
    init_db()
    if state is not None and not sm.is_state(state):
        raise ValidationError(f"unknown state filter {state!r}; valid: {', '.join(sm.ALL_STATES)}")
    conn = connect()
    try:
        if state:
            rows = conn.execute(
                "SELECT * FROM jobs WHERE state = ? ORDER BY created_at DESC LIMIT ?",
                (state, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                "SELECT * FROM jobs ORDER BY created_at DESC LIMIT ?", (limit,)
            ).fetchall()
        jobs = []
        for row in rows:
            j = _row_to_job(row)
            j["age_seconds"] = _age_seconds(j["created_at"])
            j["age"] = human_age(j["age_seconds"])
            jobs.append(j)
        return jobs
    finally:
        conn.close()


def get_job(job_id: str) -> dict:
    init_db()
    conn = connect()
    try:
        job = _fetch_job(conn, job_id)
        job["age_seconds"] = _age_seconds(job["created_at"])
        job["age"] = human_age(job["age_seconds"])
        job["allowed_transitions"] = sm.allowed_from(job["state"])
        job["terminal"] = sm.is_terminal(job["state"])
        events = [
            row_to_event(r)
            for r in conn.execute(
                "SELECT * FROM events WHERE job_id = ? ORDER BY id ASC", (job_id,)
            ).fetchall()
        ]
        job["events"] = events
        job["history"] = [
            {
                "ts": e["ts"],
                "actor": e["actor"],
                "from_state": e["from_state"],
                "to_state": e["to_state"],
                "note": e["note"],
                "kind": e["kind"],
            }
            for e in events
            if e["kind"] in ("component_invoked", "state_transition", "job_created")
        ]
        return job
    finally:
        conn.close()


def list_events(limit: int = 100, job_id: str | None = None, kind: str | None = None) -> list[dict]:
    init_db()
    limit = max(1, min(int(limit), 1000))
    sql = "SELECT * FROM events"
    clauses, params = [], []
    if job_id:
        clauses.append("job_id = ?")
        params.append(job_id)
    if kind:
        clauses.append("kind = ?")
        params.append(kind)
    if clauses:
        sql += " WHERE " + " AND ".join(clauses)
    sql += " ORDER BY id DESC LIMIT ?"
    params.append(limit)
    conn = connect()
    try:
        return [row_to_event(r) for r in conn.execute(sql, params).fetchall()]
    finally:
        conn.close()


def counts_by_state() -> dict:
    init_db()
    counts = {s: 0 for s in sm.ALL_STATES}
    conn = connect()
    try:
        for row in conn.execute("SELECT state, COUNT(*) AS n FROM jobs GROUP BY state"):
            counts[row["state"]] = row["n"]
    finally:
        conn.close()
    return counts


def chain_status() -> dict:
    init_db()
    conn = connect()
    try:
        return verify_chain(conn)
    finally:
        conn.close()


def health() -> dict:
    init_db()
    conn = connect()
    try:
        jobs = conn.execute("SELECT COUNT(*) AS n FROM jobs").fetchone()["n"]
        events = conn.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
    finally:
        conn.close()
    chain = chain_status()
    return {
        "status": "ok" if chain["ok"] else "degraded",
        "service": "jarvis-orchestrator",
        "jobs": jobs,
        "events": events,
        "event_chain_ok": chain["ok"],
        "event_chain_length": chain["length"],
        "states": sm.ALL_STATES,
        "components": len(REGISTRY.all()),
        "stubs_only": False,
        "real_components": ["IngestionLayer"],
    }


# --- seed -----------------------------------------------------------------

SEED_JOBS = [
    {
        "title": "Seed: weekly competitor pricing sweep",
        "source": "seed/manual",
        "payload": {"topic": "competitor pricing", "cadence": "weekly", "note": "seed data"},
        "advance": 0,
    },
    {
        "title": "Seed: summarise inbound support tickets",
        "source": "seed/rss",
        "payload": {"topic": "support tickets", "cadence": "daily", "note": "seed data"},
        "advance": 2,
    },
    {
        "title": "Seed: monitor changelog for breaking changes",
        "source": "seed/webhook",
        "payload": {"topic": "changelog", "cadence": "hourly", "note": "seed data"},
        "advance": 4,
    },
]


def seed_if_empty(registry: Registry | None = None) -> int:
    """Seed 3 example jobs at different states, only if the DB has no jobs."""
    init_db()
    conn = connect()
    try:
        n = conn.execute("SELECT COUNT(*) AS n FROM jobs").fetchone()["n"]
    finally:
        conn.close()
    if n:
        return 0

    created = 0
    for spec in SEED_JOBS:
        job = create_job(
            spec["title"], spec["source"], spec["payload"], is_seed=True, registry=registry
        )
        for _ in range(spec["advance"]):
            try:
                advance(job["id"], registry=registry)
            except (IllegalTransition, Exception) as exc:  # pragma: no cover - defensive
                log.warning("seed advance stopped for %s: %s", job["id"], exc)
                break
        created += 1
    log.info("seeded %d example job(s)", created)
    return created
