"""The remaining honest stubs (ingestion, verification, the bot factory and the
keep-or-kill loop are now REAL — see ingestion.py, verification.py, bot_factory.py
and measurement.py).

The two that are still registered (RunnerStub for BOT_BUILT -> RUNNING and
MeasurementStub for RUNNING -> MEASURED) do real, inspectable work on the data
structure (validates shape, counts fields, records what it looked at) and record
exactly that. Neither pretends to run a workload or to measure an outcome, and
every note is prefixed with "STUB:" so the audit log can never be mistaken for
evidence of a real run.

The INGESTED handler is no longer a stub: ``orchestrator.ingestion.IngestionLayer``
performs real HTTP fetches from free, key-less sources. It is registered here so
the registry still owns the state -> handler mapping.
"""

from __future__ import annotations

import logging

from . import state_machine as sm
from .registry import Component, Registry

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

STUB_PREFIX = "STUB:"


def _stub_log(name: str, job: dict, detail: str) -> None:
    log.info("[%s] job=%s state=%s %s", name, job.get("id"), job.get("state"), detail)


# --- 1. ingestion ---------------------------------------------------------

def ingestion_handler(job: dict) -> dict:
    """RETIRED stub, kept for reference only — never registered.

    The INGESTED handler is now ``orchestrator.ingestion.IngestionLayer``, which
    performs real network fetches. This function is never routed to.
    """
    payload = job.get("payload") or {}
    keys = sorted(payload.keys())
    note = (
        f"{STUB_PREFIX} IngestionStub accepted job from source={job.get('source')!r}; "
        f"payload has {len(keys)} top-level key(s) {keys}; no external fetch performed"
    )
    _stub_log("IngestionStub", job, note)
    return {
        "to_state": sm.INGESTED,
        "note": note,
        "payload_patch": {"_ingested": {"keys": keys, "stub": True}},
        "data": {"keys": keys, "source": job.get("source")},
    }


# --- 2. verification ------------------------------------------------------

REQUIRED_FIELDS = ("id", "title", "source")


def verification_handler(job: dict) -> dict:
    """Checks structural completeness only. It does NOT verify truth."""
    payload = job.get("payload") or {}
    missing = [f for f in REQUIRED_FIELDS if not job.get(f)]
    checks = {
        "required_fields_present": not missing,
        "missing_fields": missing,
        "title_nonempty": bool(str(job.get("title", "")).strip()),
        "source_nonempty": bool(str(job.get("source", "")).strip()),
        "payload_is_object": isinstance(payload, dict),
        "payload_key_count": len(payload),
    }
    ok = checks["required_fields_present"] and checks["payload_is_object"]
    note = (
        f"{STUB_PREFIX} VerificationStub ran {len(checks)} STRUCTURAL check(s) "
        f"(required fields, non-empty title/source, payload is object). "
        f"Result: {'pass' if ok else 'fail'}. "
        f"NO factual verification, NO source trust check, NO external lookup was performed."
    )
    _stub_log("VerificationStub", job, note)
    return {
        "to_state": sm.VERIFIED if ok else sm.FAILED,
        "note": note,
        "payload_patch": {"_verification": {"checks": checks, "stub": True}},
        "data": {"checks": checks, "structural_pass": ok, "verified_anything_real": False},
    }


# --- 3. bot factory -------------------------------------------------------

def bot_factory_handler(job: dict) -> dict:
    """RETIRED stub, kept for reference only — never registered.

    The VERIFIED handler is now ``orchestrator.bot_factory.BotFactory``, which
    builds a full deterministic spec (allowlist, denylist, cost, value, ROI, risk)
    from a VERIFIED opportunity. This placeholder spec is never produced.
    """
    payload = job.get("payload") or {}
    spec = {
        "name": f"bot-{str(job.get('id', 'unknown'))[:8]}",
        "objective": job.get("title"),
        "inputs": sorted(payload.keys()),
        "steps": ["read input", "apply rule set", "emit result"],
        "generated_code": None,
        "note": "spec only — no code was generated",
    }
    note = (
        f"{STUB_PREFIX} BotFactoryStub wrote a bot SPEC (not code) with "
        f"{len(spec['steps'])} placeholder step(s) and {len(spec['inputs'])} declared input(s); "
        f"no model was called, no artifact was built"
    )
    _stub_log("BotFactoryStub", job, note)
    return {
        "to_state": sm.BOT_BUILT,
        "note": note,
        "payload_patch": {"_bot_spec": spec},
        "data": {"bot_spec": spec, "artifact_built": False},
    }


# --- 4. runner ------------------------------------------------------------

def runner_handler(job: dict) -> dict:
    """Simulates a run by recording intent. Nothing is executed."""
    spec = (job.get("payload") or {}).get("_bot_spec") or {}
    run = {
        "mode": "dry-run",
        "executed": False,
        "steps_planned": len(spec.get("steps") or []),
        "note": "no process was spawned",
    }
    note = (
        f"{STUB_PREFIX} RunnerStub performed a DRY RUN of {run['steps_planned']} planned step(s); "
        f"no process spawned, no workload executed, no side effects"
    )
    _stub_log("RunnerStub", job, note)
    return {
        "to_state": sm.RUNNING,
        "note": note,
        "payload_patch": {"_run": run},
        "data": {"run": run},
    }


# --- 5. measurement -------------------------------------------------------

def measurement_handler(job: dict) -> dict:
    """Counts what is present in the payload. These are not performance metrics."""
    payload = job.get("payload") or {}
    metrics = {
        "payload_keys": len(payload),
        "stub_sections": sorted(k for k in payload if str(k).startswith("_")),
        "has_bot_spec": "_bot_spec" in payload,
        "has_run_record": "_run" in payload,
        "real_metrics": False,
    }
    note = (
        f"{STUB_PREFIX} MeasurementStub counted {metrics['payload_keys']} payload key(s) and "
        f"{len(metrics['stub_sections'])} stub section(s). "
        f"These are STRUCTURAL counts, not performance or quality metrics."
    )
    _stub_log("MeasurementStub", job, note)
    return {
        "to_state": sm.MEASURED,
        "note": note,
        "payload_patch": {"_measurement": metrics},
        "data": {"metrics": metrics},
    }


# --- 6. decision ----------------------------------------------------------

def decision_handler(job: dict) -> dict:
    """RETIRED stub, kept for reference only — never registered.

    The MEASURED handler is now ``orchestrator.measurement.KeepOrKillLoop``, which
    applies published rule v1.0.0 to real measurements. This structural rule is
    never applied to a job.


    Rule: keep if the bot spec exists AND the run record says dry-run completed
    AND the payload has at least 3 keys. Otherwise kill. The rule is printed in
    the note so the decision is auditable.
    """
    payload = job.get("payload") or {}
    has_spec = bool(payload.get("_bot_spec"))
    has_run = bool(payload.get("_run"))
    enough_keys = len(payload) >= 3
    keep = has_spec and has_run and enough_keys
    rule = "keep IF has_bot_spec AND has_run_record AND payload_keys>=3"
    note = (
        f"{STUB_PREFIX} DecisionStub applied the fixed rule [{rule}] -> "
        f"{'KEPT' if keep else 'KILLED'} "
        f"(has_bot_spec={has_spec}, has_run_record={has_run}, payload_keys={len(payload)}). "
        f"No model, no scoring, no human judgement involved."
    )
    _stub_log("DecisionStub", job, note)
    return {
        "to_state": sm.KEPT if keep else sm.KILLED,
        "note": note,
        "payload_patch": {"_decision": {"rule": rule, "kept": keep}},
        "data": {"rule": rule, "kept": keep},
    }


# --- registration ---------------------------------------------------------

def register_default_components(registry: Registry) -> Registry:
    """Register the six shipped stubs. Idempotent per registry instance."""
    specs = [
        # NOTE: VerificationStub used to be registered here for INGESTED. It has
        # been replaced by the REAL orchestrator.verification.VerificationLayer
        # (registered at the bottom of this function), which re-fetches sources.
        # NOTE: BotFactoryStub (VERIFIED) and DecisionStub (MEASURED) are gone too:
        # they have been replaced by the REAL orchestrator.bot_factory.BotFactory
        # and orchestrator.measurement.KeepOrKillLoop, both registered below.
        Component(
            name="RunnerStub",
            handles_state=sm.BOT_BUILT,
            handler=runner_handler,
            description="Dry run only. Spawns no process.",
            produces_state=sm.RUNNING,
        ),
        Component(
            name="MeasurementStub",
            handles_state=sm.RUNNING,
            handler=measurement_handler,
            description="Structural counts only. No real metrics.",
            produces_state=sm.MEASURED,
        ),
    ]
    for spec in specs:
        if not registry.has(spec.name):
            registry.register(spec)
    # Real ingestion layer replaces the old IngestionStub as the INGESTED handler.
    from .ingestion import register_ingestion

    register_ingestion(registry)

    # REAL verification layer replaces VerificationStub as the INGESTED -> VERIFIED
    # handler. It re-fetches every cited source and gates the transition on a real
    # verdict. Registered through the registry — the router is not edited.
    from .verification import register_verification

    register_verification(registry)

    # The opportunity engine is a REAL tool component: it is registered here so
    # callers resolve it through the registry, but it owns no pipeline state and
    # therefore cannot be routed to by the state machine.
    from .opportunity import register_opportunity_engine

    register_opportunity_engine(registry)

    # THE BOT FACTORY: the VERIFIED -> BOT_BUILT handler. Deterministic specs
    # (allowlist, denylist, cost, value, ROI, risk); refuses anything that is not
    # VERIFIED with a 409, enforced again at the state-machine boundary.
    from .bot_factory import register_bot_factory

    register_bot_factory(registry)

    # THE KEEP-OR-KILL LOOP: the MEASURED -> KEPT|KILLED handler. Applies the
    # published rule version to the latest measurement. No model judgement.
    from .measurement import register_keep_or_kill

    register_keep_or_kill(registry)

    # THE SCHEDULING LAYER: a tool component (no pipeline state). Tick-driven,
    # not a daemon — every run is caused by a request and audited.
    from .scheduling import register_scheduling

    register_scheduling(registry)

    # LOCAL VOICE: a tool component. Routes a transcript to the existing layers
    # with deterministic keyword matching; the audio never leaves the browser.
    from .voice import register_voice

    register_voice(registry)

    # PHONE REACH: a tool component. The installable PWA shell (manifest,
    # versioned service worker, mobile CSS, generated icons) plus the one-tap
    # phone actions. NOT telephony: no number, no SMS, no calls.
    from .pwa import register_phone_reach

    register_phone_reach(registry)

    # THE AVATAR: a tool component. The browser-rendered three.js front door.
    # Its states are driven by real speech/command events and it visualises no
    # cognition — a visual front door, not a model of the system's thinking.
    from .avatar import register_avatar

    register_avatar(registry)
    return registry
