"""THE BOT FACTORY — a deterministic, rule-based bot-spec builder.

What it is
----------
Taking a **VERIFIED** opportunity, this component emits one concrete,
inspectable artifact: a bot SPEC. It is not a bot, not deployed code and not a
service. The spec says what a bot would do, what it may touch, what it may never
touch, and what it would cost.

What it is not
--------------
No model is called (``model_calls: 0``). No clock is read while scoring, no
randomness is used and no network request is made: the same opportunity row in
produces byte-identical spec JSON out, which is why ``spec_hash`` (sha256 of the
canonical JSON) can be used later to prove a spec has not been edited.

Hard rule
---------
The factory refuses to build for an opportunity whose stored verification
verdict is not ``VERIFIED``. It raises ``BotBuildBlocked`` (HTTP 409) naming the
verdict and the blocking citations, and the state-machine boundary
(``state_machine.assert_bot_build_gate``, called by ``service.advance``) refuses
the same VERIFIED -> BOT_BUILT edge independently — the same double-check
pattern the verification gate uses.

The cost / value / ROI arithmetic is stored verbatim in the spec so every number
can be re-derived by hand. Every figure is an ESTIMATE from a documented model:
no revenue has been earned by any of these bots, because none of them has run.
"""

from __future__ import annotations

import hashlib
import json
import logging

from . import audit
from . import state_machine as sm
from .db import CURRENT_CONN, LOCK, connect, init_db
from .errors import BotBuildBlocked, ValidationError
from .events import canonical, utcnow
from .registry import Component, Registry

try:
    from .contract import attach_contract, contract_gaps
except ImportError:  # pragma: no cover - direct script execution
    from contract import attach_contract, contract_gaps


class BotContractIncomplete(Exception):
    """Raised when a spec would be stored without its component contract."""

    def __init__(self, bot_id, gaps):
        self.bot_id = bot_id
        self.gaps = list(gaps)
        super().__init__(
            "refusing to store spec %r — contract incomplete: %s"
            % (bot_id, "; ".join(self.gaps))
        )

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

COMPONENT_NAME = "BotFactory"
SPEC_VERSION = "1.0.0"
COST_MODEL_VERSION = "1.0.0"
VALUE_MODEL_VERSION = "1.0.0"
RISK_MODEL_VERSION = "1.0.0"

HONESTY = (
    "This is a generated SPEC, not a deployed bot. No code was produced, no process was "
    "spawned and this bot has never executed. Cost and value figures are ESTIMATES from the "
    "documented model below, not measured telemetry."
)

# --- the safety boundary ---------------------------------------------------
#: Everything a bot of this kind may touch. Anything not listed is refused.
BASE_ALLOWLIST = ["read_owner_config", "read_knowledge_base", "log_event", "notify_owner"]

#: Never, under any input, by any bot this factory builds.
DENYLIST = [
    "send_money",
    "move_funds",
    "issue_refund",
    "delete_data",
    "drop_table",
    "rotate_credentials",
    "contact_list_without_approval",
    "send_external_email_without_approval",
    "post_public_without_approval",
    "sign_contract",
    "file_legal_document",
    "change_live_price",
    "close_account",
    "modify_source_of_truth",
]

#: Actions that put something into the outside world. If a spec CONTAINS one of
#: these, it sits next to a denylisted outcome (an unreviewed send, publish or
#: contact), so the bot must be human-approved before it is ever run.
ADJACENT_ACTIONS = [
    "send_reply",
    "send_newsletter",
    "post_to_slack",
    "open_pull_request",
    "publish_listing",
    "schedule_post",
    "schedule_interview",
    "message_driver",
]

# --- cost model ------------------------------------------------------------
#: Runs per month per topic, from an assumption about how often the underlying
#: event happens for one small customer. An ASSUMPTION, printed in the spec.
RUNS_PER_MONTH = {
    "ai-tooling": 4000,
    "small-business-ops": 6000,
    "commerce-payments": 3000,
    "security-compliance": 1500,
    "chips-hardware": 400,
    "dev-tools": 2500,
    "content-media": 2000,
    "housing-local": 800,
    "jobs-labour": 900,
    "mobility-logistics": 5000,
}
DEFAULT_RUNS_PER_MONTH = 1000
COST_PER_RUN_BASE_USD = 0.020
COST_PER_STEP_USD = 0.005
FIXED_INFRA_USD = 18.00

#: estimated_monthly_value_usd = money_potential/100 * feasibility/100 * VALUE_CEILING_USD
VALUE_CEILING_USD = 1500.00

# --- risk model ------------------------------------------------------------
HIGH_RISK_TOPICS = ("security-compliance", "commerce-payments", "housing-local", "jobs-labour")

#: How many measurements a spec needs before a keep/kill verdict is even possible.
MIN_MEASUREMENTS_FOR_VERDICT = 1

# --------------------------------------------------------------------------
# Per-topic bot templates — the deterministic input to build_spec().
# --------------------------------------------------------------------------

def _step(action: str, detail: str, reads: list[str], writes: list[str]) -> dict:
    return {"action": action, "detail": detail, "reads": reads, "writes": writes}


BOT_TEMPLATES: dict[str, dict] = {
    "ai-tooling": {
        "slug": "assistant-layer",
        "purpose": (
            "Sits on top of the models a team already pays for and turns raw model traffic into "
            "governed output: routes each request to a cheaper model, enforces a per-team cost "
            "cap, scores the answer against a fixed rubric and parks anything below the rubric "
            "in a human review queue instead of returning it."
        ),
        "trigger": ("event", "a new prompt-run event arrives from the customer's API gateway"),
        "steps": [
            _step("read_prompt_log", "pull the latest prompt-run record from the gateway log",
                  ["store:prompt_runs"], []),
            _step("classify_task", "map the request to a task class with keyword rules",
                  ["store:prompt_runs", "config:routing_table"], ["store:task_labels"]),
            _step("apply_cost_cap", "refuse or downgrade the model when the team's monthly cap is hit",
                  ["store:usage_counters", "config:cost_cap"], ["store:usage_counters"]),
            _step("score_output", "score the answer against the eval rubric",
                  ["store:prompt_runs", "config:eval_rubric"], ["store:eval_scores"]),
            _step("draft_reply", "draft a review note for any answer under the rubric threshold",
                  ["store:eval_scores"], ["store:review_queue"]),
            _step("notify_owner", "tell the owner a review is waiting", ["store:review_queue"], []),
        ],
        "inputs": {
            "prompt_run_id": "string",
            "team_id": "string",
            "task_text": "string (<= 8000 chars)",
            "requested_model": "string",
        },
        "outputs": {
            "task_class": "string",
            "chosen_model": "string",
            "output_score": "number (0-1)",
            "review_required": "boolean",
            "review_note": "string|null",
        },
        "extra_allowed": ["read_prompt_log", "classify_task", "apply_cost_cap", "score_output",
                          "draft_reply"],
    },
    "small-business-ops": {
        "slug": "backoffice-clerk",
        "purpose": (
            "Reads the inbound email and ticket queue of an owner-operated business, sorts each "
            "message into an explicit category, drafts the reply and the invoice chase, and puts "
            "every draft in front of the owner. It never sends anything on its own and never "
            "touches money — the owner presses send."
        ),
        "trigger": ("event", "a new inbound message arrives in the shared inbox"),
        "steps": [
            _step("read_inbox", "fetch new messages from the connected mailbox",
                  ["inbox:messages"], []),
            _step("classify_message", "label the message with keyword rules (quote, complaint, invoice, other)",
                  ["inbox:messages", "config:labels"], ["store:message_labels"]),
            _step("draft_reply", "draft a reply from the approved templates plus the message facts",
                  ["store:message_labels", "config:templates"], ["store:drafts"]),
            _step("draft_invoice_chase", "draft a chase note for overdue invoices (no payment is taken)",
                  ["store:invoices", "config:templates"], ["store:drafts"]),
            _step("notify_owner", "queue the drafts for the owner's approval",
                  ["store:drafts"], ["store:approval_queue"]),
        ],
        "inputs": {
            "message_id": "string",
            "from": "string",
            "subject": "string",
            "body_text": "string (<= 20000 chars)",
            "received_at": "string (ISO-8601)",
        },
        "outputs": {
            "label": "string",
            "draft_reply": "string|null",
            "draft_invoice_chase": "string|null",
            "needs_owner_approval": "boolean (always true)",
        },
        "extra_allowed": ["read_inbox", "classify_message", "draft_reply", "draft_invoice_chase"],
    },
    "commerce-payments": {
        "slug": "listing-pricer",
        "purpose": (
            "Reads a seller's listings and the public prices of comparable items, drafts a "
            "rewritten listing and a suggested price band, and explains the reasoning. It "
            "proposes; the seller publishes. It cannot change a live price and cannot move money."
        ),
        "trigger": ("schedule", "every day at a fixed hour, plus a webhook when a listing is edited"),
        "steps": [
            _step("read_listings", "pull the seller's active listings",
                  ["store:listings"], []),
            _step("fetch_competitor_prices", "read public competitor prices for comparable items",
                  ["web:public_listings"], ["store:price_observations"]),
            _step("draft_listing", "rewrite title, bullets and description from the observed facts",
                  ["store:listings", "store:price_observations"], ["store:drafts"]),
            _step("propose_price", "compute a suggested price band with a documented margin rule",
                  ["store:price_observations", "config:margin_rules"], ["store:drafts"]),
            _step("notify_owner", "hand the drafts and the price band to the seller",
                  ["store:drafts"], ["store:approval_queue"]),
        ],
        "inputs": {
            "seller_id": "string",
            "listing_ids": "array[string]",
            "observed_competitor_prices": "array[{sku, price_usd, url}]",
        },
        "outputs": {
            "listing_drafts": "array[{listing_id, title, bullets, description}]",
            "price_band": "{low_usd, high_usd, rule}",
            "publish_requires_human": "boolean (always true)",
        },
        "extra_allowed": ["read_listings", "fetch_competitor_prices", "draft_listing",
                          "propose_price"],
    },
    "security-compliance": {
        "slug": "incident-triage",
        "purpose": (
            "Turns public advisories, CVE feeds and outage reports into a prioritised patch list "
            "for a small engineering team, and drafts the customer-facing disclosure for a human "
            "to review. It cannot publish, cannot contact customers and cannot change "
            "infrastructure."
        ),
        "trigger": ("schedule", "every 6 hours, plus a webhook when a new advisory is published"),
        "steps": [
            _step("read_advisories", "read the advisory and CVE feeds the team subscribes to",
                  ["feed:advisories", "feed:cve"], ["store:advisories"]),
            _step("match_inventory", "match each advisory against the team's declared dependency list",
                  ["store:advisories", "store:dependency_inventory"], ["store:matches"]),
            _step("rank_patches", "rank matches by exploitability and required patch effort",
                  ["store:matches", "config:risk_weights"], ["store:patch_list"]),
            _step("draft_disclosure", "draft a customer-facing note for matched incidents at all",
                  ["store:patch_list", "config:disclosure_template"], ["store:drafts"]),
            _step("notify_owner", "hand the patch list and drafts to the on-call engineer",
                  ["store:patch_list", "store:drafts"], ["store:approval_queue"]),
        ],
        "inputs": {
            "advisory_ids": "array[string]",
            "dependency_inventory": "array[{package, version}]",
            "severity_weights": "object (optional override of the fixed weights)",
        },
        "outputs": {
            "patch_list": "array[{advisory_id, package, priority, rationale}]",
            "disclosure_draft": "string|null",
            "publish_requires_human": "boolean (always true)",
        },
        "extra_allowed": ["read_advisories", "match_inventory", "rank_patches",
                          "draft_disclosure"],
    },
    "chips-hardware": {
        "slug": "supply-brief",
        "purpose": (
            "Watches supplier, capacity and export-control news for chip and infrastructure "
            "buyers and writes a short weekly risk brief with a citation on every claim. The "
            "citation gate drops any sentence whose source cannot be quoted."
        ),
        "trigger": ("schedule", "weekly, on a fixed day, over the last 7 days of public news"),
        "steps": [
            _step("read_feeds", "read the configured supplier and industry feeds",
                  ["feed:supply_news"], ["store:articles"]),
            _step("extract_claims", "extract one claim per article with its source URL",
                  ["store:articles"], ["store:claims"]),
            _step("drop_uncited", "drop any claim that has no quotable source",
                  ["store:claims"], ["store:claims_cited"]),
            _step("draft_brief", "write the brief strictly from the surviving claims",
                  ["store:claims_cited", "config:brief_template"], ["store:drafts"]),
            _step("notify_owner", "hand the draft brief to the analyst for review",
                  ["store:drafts"], ["store:approval_queue"]),
        ],
        "inputs": {
            "window_days": "integer (default 7)",
            "feed_ids": "array[string]",
            "buyer_segment": "string",
        },
        "outputs": {
            "brief_markdown": "string",
            "claims": "array[{claim, source_url, published_at}]",
            "dropped_uncited": "integer",
            "send_requires_human": "boolean (always true)",
        },
        "extra_allowed": ["read_feeds", "extract_claims", "drop_uncited", "draft_brief"],
    },
    "dev-tools": {
        "slug": "migration-agent",
        "purpose": (
            "Reads release notes and changelogs for a repository's pinned dependencies, flags "
            "breaking changes that touch the codebase, and prepares an upgrade branch with the "
            "mechanical fixes and a test run. A human merges the pull request."
        ),
        "trigger": ("event", "a dependency release webhook, plus a weekly scheduled scan"),
        "steps": [
            _step("read_changelog", "read the release notes of pinned dependencies",
                  ["web:release_notes"], ["store:release_notes"]),
            _step("analyse_repo", "map breaking-change symbols onto the repo's imports",
                  ["store:release_notes", "repo:source_tree"], ["store:impact_list"]),
            _step("draft_patch", "write the mechanical version bump and import fixes on a branch",
                  ["store:impact_list", "repo:source_tree"], ["repo:branch"]),
            _step("open_pull_request", "open a pull request with the diff and the impact list",
                  ["repo:branch", "store:impact_list"], ["repo:pull_request"]),
            _step("notify_owner", "tell the maintainer the PR is ready for review",
                  ["repo:pull_request"], []),
        ],
        "inputs": {
            "repo": "string (owner/name)",
            "dependency": "string",
            "from_version": "string",
            "to_version": "string",
            "release_notes_url": "string (http/https)",
        },
        "outputs": {
            "breaking_changes": "array[{symbol, note, source_url}]",
            "branch": "string",
            "pull_request_url": "string",
            "tests_passed": "boolean|null",
        },
        "extra_allowed": ["read_changelog", "analyse_repo", "draft_patch",
                          "open_pull_request"],
    },
    "content-media": {
        "slug": "repurposing-desk",
        "purpose": (
            "Turns one published article into channel-specific drafts for an independent "
            "publisher and keeps every claim linked to the source paragraph. It drafts and "
            "schedules for review; it does not publish without a human."
        ),
        "trigger": ("event", "a new article is published on the publisher's own site"),
        "steps": [
            _step("read_article", "read the article body and its canonical URL",
                  ["store:articles"], ["store:articles"]),
            _step("extract_claims", "split the article into claims with their source paragraph",
                  ["store:articles"], ["store:claims"]),
            _step("draft_channel_variants", "draft the newsletter, social and video-script variants",
                  ["store:claims", "config:channel_templates"], ["store:drafts"]),
            _step("attach_citations", "attach the source URL and paragraph to every draft claim",
                  ["store:claims", "store:drafts"], ["store:drafts"]),
            _step("notify_owner", "queue the variants for the editor",
                  ["store:drafts"], ["store:approval_queue"]),
        ],
        "inputs": {
            "article_url": "string (http/https)",
            "article_text": "string",
            "channels": "array[string] (newsletter|social|script)",
        },
        "outputs": {
            "variants": "array[{channel, text, citations}]",
            "uncited_claims_dropped": "integer",
            "publish_requires_human": "boolean (always true)",
        },
        "extra_allowed": ["read_article", "extract_claims", "draft_channel_variants",
                          "attach_citations"],
    },
    "housing-local": {
        "slug": "paperwork-reader",
        "purpose": (
            "Reads tenancy, mortgage and notice paperwork for small landlords and first-time "
            "buyers, extracts the deadlines and amounts that actually appear in the document, "
            "and drafts the covering letter. It never signs, files or sends anything."
        ),
        "trigger": ("event", "a document is uploaded to the workspace"),
        "steps": [
            _step("read_document", "extract the text of the uploaded document",
                  ["store:documents"], ["store:document_text"]),
            _step("extract_dates_amounts", "pull dates, amounts and party names with their page reference",
                  ["store:document_text"], ["store:extractions"]),
            _step("flag_deadlines", "flag deadlines falling inside the next 30 days",
                  ["store:extractions"], ["store:deadlines"]),
            _step("draft_letter", "draft the covering letter from the extracted facts",
                  ["store:extractions", "config:letter_templates"], ["store:drafts"]),
            _step("notify_owner", "hand the extraction, deadlines and draft to the owner",
                  ["store:deadlines", "store:drafts"], ["store:approval_queue"]),
        ],
        "inputs": {
            "document_id": "string",
            "document_text": "string",
            "party_role": "string (landlord|tenant|buyer)",
        },
        "outputs": {
            "dates": "array[{label, date, page}]",
            "amounts": "array[{label, amount_gbp, page}]",
            "deadlines_30d": "array[{label, date}]",
            "draft_letter": "string|null",
            "sign_or_file_requires_human": "boolean (always true)",
        },
        "extra_allowed": ["read_document", "extract_dates_amounts", "flag_deadlines",
                          "draft_letter"],
    },
    "jobs-labour": {
        "slug": "hiring-copilot",
        "purpose": (
            "Writes the role spec, screens applications against criteria the employer wrote "
            "down in advance, and proposes a shortlist with a reason for every rejection. A "
            "human makes every hiring decision; the bot cannot contact candidates."
        ),
        "trigger": ("event", "a new application arrives for an open role"),
        "steps": [
            _step("draft_role_spec", "draft the role spec from the employer's stated requirements",
                  ["config:role_inputs"], ["store:role_specs"]),
            _step("screen_application", "score the application against the published criteria",
                  ["store:applications", "config:criteria"], ["store:screening"]),
            _step("propose_shortlist", "rank the screened applications and write the reason for each",
                  ["store:screening"], ["store:shortlists"]),
            _step("notify_owner", "hand the shortlist to the employer for a human decision",
                  ["store:shortlists"], ["store:approval_queue"]),
        ],
        "inputs": {
            "role_id": "string",
            "criteria": "array[{criterion, weight}]",
            "application_text": "string",
        },
        "outputs": {
            "criteria_scores": "array[{criterion, score, evidence_quote}]",
            "shortlist_rank": "integer|null",
            "reason": "string",
            "decision_made_by": "human (always)",
        },
        "extra_allowed": ["draft_role_spec", "screen_application", "propose_shortlist"],
    },
    "mobility-logistics": {
        "slug": "dispatcher",
        "purpose": (
            "Reads incoming delivery orders, sequences them into routes that respect each "
            "driver's declared shift, drafts the driver messages and escalates exceptions to a "
            "human. It cannot book, pay or cancel anything."
        ),
        "trigger": ("event", "a new order is accepted into the dispatch queue"),
        "steps": [
            _step("read_orders", "read the new orders and the current driver roster",
                  ["store:orders", "store:drivers"], []),
            _step("sequence_routes", "sequence each driver's stops with the fixed travel-time table",
                  ["store:orders", "store:drivers", "config:travel_times"], ["store:routes"]),
            _step("draft_driver_messages", "draft the stop list for each driver",
                  ["store:routes"], ["store:drafts"]),
            _step("escalate_exceptions", "flag orders that break a shift or a capacity limit",
                  ["store:routes", "config:capacity_limits"], ["store:exceptions"]),
            _step("notify_owner", "send the plan to the dispatcher for approval",
                  ["store:routes", "store:exceptions"], ["store:approval_queue"]),
        ],
        "inputs": {
            "order_ids": "array[string]",
            "driver_roster": "array[{driver_id, shift_start, shift_end, capacity}]",
            "travel_time_table": "object",
        },
        "outputs": {
            "routes": "array[{driver_id, stops, eta_minutes}]",
            "exceptions": "array[{order_id, reason}]",
            "send_requires_human": "boolean (always true)",
        },
        "extra_allowed": ["read_orders", "sequence_routes", "draft_driver_messages",
                          "escalate_exceptions"],
    },
}

GENERIC_TEMPLATE = {
    "slug": "rule-runner",
    "purpose": (
        "Applies a fixed rule set to one class of inbound item, records what it read and what it "
        "decided, and hands anything it cannot classify to a human."
    ),
    "trigger": ("event", "a new item arrives from the configured source"),
    "steps": [
        _step("read_item", "read the inbound item", ["source:items"], []),
        _step("classify_item", "classify the item with keyword rules",
              ["source:items", "config:rules"], ["store:labels"]),
        _step("draft_output", "draft the output for the classified item",
              ["store:labels", "config:templates"], ["store:drafts"]),
        _step("notify_owner", "hand the draft to the owner", ["store:drafts"],
              ["store:approval_queue"]),
    ],
    "inputs": {"item_id": "string", "text": "string"},
    "outputs": {"label": "string", "draft": "string|null", "needs_review": "boolean"},
    "extra_allowed": ["read_item", "classify_item", "draft_output"],
}


# --------------------------------------------------------------------------
# Pure builder — deterministic, no clock, no randomness, no model
# --------------------------------------------------------------------------

def topic_key(opp: dict) -> str:
    key = (opp.get("cluster_key") or "").strip()
    return key if key in BOT_TEMPLATES else ""


def _slug(text: str) -> str:
    out = []
    for ch in str(text or "").lower():
        if ch.isalnum():
            out.append(ch)
        elif out and out[-1] != "-":
            out.append("-")
    return "".join(out).strip("-") or "bot"


def bot_name_for(opp: dict) -> str:
    """Deterministic: topic slug + first 6 hex of sha256(opportunity id)."""
    key = topic_key(opp)
    template = BOT_TEMPLATES.get(key, GENERIC_TEMPLATE)
    digest = hashlib.sha256(str(opp.get("id", "")).encode("utf-8")).hexdigest()[:6]
    return f"bot-{template['slug']}-{digest}"


def _score_value(opp: dict, name: str, default: int = 0) -> int:
    scores = opp.get("scores") or {}
    try:
        return int(scores[name]["value"])
    except (KeyError, TypeError, ValueError):
        return default


def cost_model(steps: list[dict], key: str) -> dict:
    """Documented cost model, with the arithmetic kept as a string."""
    runs = RUNS_PER_MONTH.get(key, DEFAULT_RUNS_PER_MONTH)
    per_run = round(COST_PER_RUN_BASE_USD + COST_PER_STEP_USD * len(steps), 4)
    variable = round(runs * per_run, 2)
    total = round(variable + FIXED_INFRA_USD, 2)
    return {
        "version": COST_MODEL_VERSION,
        "formula": "runs_per_month * cost_per_run_usd + fixed_infra_usd",
        "cost_per_run_formula": f"{COST_PER_RUN_BASE_USD} + {COST_PER_STEP_USD} * step_count",
        "runs_per_month": runs,
        "runs_per_month_basis": f"assumed demand for topic {key or 'generic'} (ASSUMPTION, not measured)",
        "step_count": len(steps),
        "cost_per_run_usd": per_run,
        "variable_cost_usd": variable,
        "fixed_infra_usd": FIXED_INFRA_USD,
        "estimated_monthly_cost_usd": total,
        "arithmetic": (
            f"{runs} runs * ${per_run:.4f}/run = ${variable:.2f}; "
            f"${variable:.2f} + ${FIXED_INFRA_USD:.2f} fixed = ${total:.2f}"
        ),
        "assumptions": [
            "one run per inbound item for the assumed monthly volume",
            "compute is charged at the published base rate plus a per-step rate",
            f"fixed hosting and monitoring is ${FIXED_INFRA_USD:.2f}/month",
            "no marketing, support or labour cost is included",
        ],
        "measured": False,
    }


def value_model(opp: dict) -> dict:
    money = _score_value(opp, "money_potential")
    feas = _score_value(opp, "feasibility")
    value = round((money / 100.0) * (feas / 100.0) * VALUE_CEILING_USD, 2)
    return {
        "version": VALUE_MODEL_VERSION,
        "formula": "money_potential/100 * feasibility/100 * VALUE_CEILING_USD",
        "money_potential": money,
        "feasibility": feas,
        "value_ceiling_usd": VALUE_CEILING_USD,
        "estimated_monthly_value_usd": value,
        "arithmetic": (
            f"{money}/100 * {feas}/100 * ${VALUE_CEILING_USD:.2f} = ${value:.2f}"
        ),
        "assumptions": [
            "VALUE_CEILING_USD is the monthly value of a bot serving one customer perfectly at "
            "money_potential 100 and feasibility 100",
            "the opportunity's own money-potential and feasibility sub-scores scale that ceiling",
            "this is an ESTIMATE from the scoring rules; no customer has paid anything",
        ],
        "measured": False,
    }


def risk_model(opp: dict, key: str, steps: list[dict]) -> dict:
    feas = _score_value(opp, "feasibility")
    conf = _score_value(opp, "confidence")
    adjacent = sorted({s["action"] for s in steps if s["action"] in ADJACENT_ACTIONS})
    if key in HIGH_RISK_TOPICS:
        level, why = "high", f"topic {key!r} is on the high-risk list (money, personal data, legal or hiring decisions)"
    elif feas < 60:
        level, why = "high", f"feasibility {feas} < 60"
    elif feas < 80 or conf < 60:
        level, why = "medium", f"feasibility {feas} < 80 or confidence {conf} < 60"
    else:
        level, why = "low", f"feasibility {feas} >= 80 and confidence {conf} >= 60"
    return {
        "version": RISK_MODEL_VERSION,
        "level": level,
        "rule": (
            "high IF topic in HIGH_RISK_TOPICS OR feasibility < 60; "
            "ELSE medium IF feasibility < 80 OR confidence < 60; ELSE low"
        ),
        "inputs": {"topic": key or "generic", "feasibility": feas, "confidence": conf,
                   "high_risk_topics": list(HIGH_RISK_TOPICS)},
        "why": why,
        "adjacent_outbound_actions": adjacent,
    }


def build_spec(opp: dict) -> dict:
    """The spec for one opportunity. Pure: same opportunity in -> same spec out."""
    key = topic_key(opp)
    template = BOT_TEMPLATES.get(key, GENERIC_TEMPLATE)
    steps = [
        {"n": i + 1, **step, "reads": list(step["reads"]), "writes": list(step["writes"])}
        for i, step in enumerate(template["steps"])
    ]
    allowlist = sorted(set(BASE_ALLOWLIST) | set(template["extra_allowed"]))
    invalid = sorted(set(allowlist) & set(DENYLIST))
    if invalid:  # pragma: no cover - guards the template table itself
        raise ValidationError(f"bot template for {key!r} allowlists denylisted actions: {invalid}")

    costs = cost_model(steps, key)
    value = value_model(opp)
    cost_usd = costs["estimated_monthly_cost_usd"]
    value_usd = value["estimated_monthly_value_usd"]
    roi = round(value_usd / cost_usd, 2) if cost_usd else None

    risk = risk_model(opp, key, steps)
    approval = risk["level"] == "high" or bool(risk["adjacent_outbound_actions"])
    reasons = []
    if risk["level"] == "high":
        reasons.append(f"risk level is high ({risk['why']})")
    if risk["adjacent_outbound_actions"]:
        reasons.append(
            "the spec contains outbound action(s) adjacent to a denylisted outcome: "
            + ", ".join(risk["adjacent_outbound_actions"])
        )
    if not reasons:
        reasons.append("risk is not high and no step reaches outside the workspace without review")

    trigger_type, trigger_detail = template["trigger"]
    purpose = f"{template['purpose']} It exists for: {opp.get('what_they_need', '').strip()}"

    spec = {
        "spec_version": SPEC_VERSION,
        "generator": COMPONENT_NAME,
        "generated": True,
        "honesty": HONESTY,
        "model_calls": 0,
        "deterministic": True,
        "opportunity": {
            "id": opp.get("id"),
            "title": opp.get("title"),
            "business_type": opp.get("business_type"),
            "topic": key or "generic",
            "topic_label": opp.get("cluster_label") or key or "generic",
            "composite_score": opp.get("composite_score"),
            "scores": {n: _score_value(opp, n) for n in
                       ("signal_strength", "money_potential", "feasibility", "confidence")},
            "verdict": opp.get("verdict"),
            "verdict_rule_version": opp.get("verdict_rule_version"),
            "evidence_signal_ids": [
                e.get("signal_id") for e in (opp.get("evidence") or []) if e.get("signal_id")
            ],
        },
        "bot_name": bot_name_for(opp),
        "purpose": purpose,
        "trigger": {
            "type": trigger_type,
            "detail": trigger_detail,
            "runs_per_month": costs["runs_per_month"],
        },
        "steps": steps,
        "inputs": {
            "schema_version": SPEC_VERSION,
            "fields": template["inputs"],
            "source": f"topic template {key or 'generic'}",
        },
        "outputs": {
            "schema_version": SPEC_VERSION,
            "fields": template["outputs"],
        },
        "allowed_actions": allowlist,
        "denied_actions": list(DENYLIST),
        "safety_boundary": {
            "allowlist": allowlist,
            "denylist": list(DENYLIST),
            "adjacent_denied_actions": risk["adjacent_outbound_actions"],
            "rule": (
                "the bot may call ONLY the actions in the allowlist; every denylisted action is "
                "refused before it reaches a tool, whatever the input says"
            ),
            "enforcement_point": "the tool dispatcher checks the allowlist; the denylist is checked "
                                 "first and cannot be widened by the spec",
        },
        "cost_model": costs,
        "value_model": value,
        "estimated_monthly_cost_usd": cost_usd,
        "estimated_monthly_value_usd": value_usd,
        "roi_ratio": roi,
        "roi_arithmetic": f"${value_usd:.2f} value / ${cost_usd:.2f} cost = {roi}",
        "risk": risk,
        "risk_level": risk["level"],
        "requires_human_approval": approval,
        "approval_reason": "; ".join(reasons),
        "deployment": {
            "deployed": False,
            "note": "spec only — nothing was deployed and no process was started",
        },
    }
    return attach_contract(spec, MIN_MEASUREMENTS_FOR_VERDICT)


def spec_hash(spec: dict) -> str:
    """sha256 of the canonical JSON, so a spec can be proven unchanged later."""
    return hashlib.sha256(canonical(spec).encode("utf-8")).hexdigest()


# --------------------------------------------------------------------------
# Persistence
# --------------------------------------------------------------------------

COLUMNS = ("id", "opportunity_id", "job_id", "spec_json", "created_at", "spec_hash",
           "status", "retired", "retired_at", "trigger")


def _decode(row) -> dict:
    d = dict(row)
    try:
        d["spec"] = json.loads(d.get("spec_json") or "{}")
    except (ValueError, TypeError):
        d["spec"] = {}
    d["retired"] = bool(d.get("retired"))
    spec = d["spec"] or {}
    d["bot_name"] = spec.get("bot_name")
    d["risk_level"] = spec.get("risk_level")
    d["estimated_monthly_cost_usd"] = spec.get("estimated_monthly_cost_usd")
    d["estimated_monthly_value_usd"] = spec.get("estimated_monthly_value_usd")
    d["roi_ratio"] = spec.get("roi_ratio")
    d["requires_human_approval"] = spec.get("requires_human_approval")
    d["hash_ok"] = spec_hash(spec) == d.get("spec_hash") if spec else False
    return d


def _load_opportunity(conn, opp_id: str) -> dict:
    row = conn.execute("SELECT * FROM opportunities WHERE id = ?", (opp_id,)).fetchone()
    if row is None:
        raise ValidationError(f"no opportunity with id {opp_id!r}")
    opp = dict(row)
    try:
        opp["scores"] = json.loads(opp.get("scores") or "{}")
    except (ValueError, TypeError):
        opp["scores"] = {}
    try:
        opp["evidence"] = json.loads(opp.get("evidence") or "[]")
    except (ValueError, TypeError):
        opp["evidence"] = []
    return opp


def _blocking_citations(opp: dict) -> list[dict]:
    verification_blob = opp.get("verification")
    if isinstance(verification_blob, str):
        try:
            verification_blob = json.loads(verification_blob or "{}")
        except (ValueError, TypeError):
            verification_blob = {}
    blob = verification_blob if isinstance(verification_blob, dict) else {}
    citations = blob.get("citations") or []
    return [c for c in citations if c.get("outcome") != "confirmed"]


def _refusal(opp: dict) -> BotBuildBlocked:
    verdict = opp.get("verdict")
    where = opp.get("id")
    message = (
        f"bot factory refused to build for opportunity {where}: verification verdict is "
        f"{verdict or 'NO VERDICT'}"
        + (f" (rule v{opp.get('verdict_rule_version')})" if opp.get("verdict_rule_version") else "")
        + ". Only a VERIFIED opportunity may be turned into a bot spec."
    )
    blocking = _blocking_citations(opp)
    if blocking:
        message += " Blocking citations: " + "; ".join(
            f"{c.get('signal_id')} {c.get('source')} {c.get('url')} -> {c.get('outcome')}: "
            f"{(c.get('saw') or c.get('error') or 'no detail')[:180]}"
            for c in blocking[:4]
        )
    elif verdict is None:
        message += (
            " No verification has been recorded for this opportunity — run "
            "POST /opportunities/<id>/verify first."
        )
    return BotBuildBlocked(
        message,
        verdict=verdict,
        details={
            "verdict": verdict,
            "rule_version": opp.get("verdict_rule_version"),
            "opportunity_id": where,
            "verdict_at": opp.get("verdict_at"),
            "blocking_signal_ids": [c.get("signal_id") for c in blocking],
        },
    )


def build_bot(
    opp_id: str,
    *,
    trigger: str = "api",
    job_id: str | None = None,
    force: bool = False,
    write_audit: bool = True,
) -> dict:
    """Build (or reuse) a spec for one opportunity. Refuses anything not VERIFIED."""
    init_db()
    ambient = CURRENT_CONN.get()

    def _work(conn) -> dict:
        opp = _load_opportunity(conn, opp_id)
        if (opp.get("verdict") or None) != "VERIFIED":
            raise _refusal(opp)

        existing = None
        if not force:
            if job_id:
                row = conn.execute(
                    "SELECT * FROM bot_specs WHERE job_id = ? ORDER BY id DESC LIMIT 1", (job_id,)
                ).fetchone()
                existing = row
            if existing is None:
                row = conn.execute(
                    "SELECT * FROM bot_specs WHERE opportunity_id = ? AND job_id IS ? "
                    "ORDER BY id DESC LIMIT 1",
                    (opp_id, job_id),
                ).fetchone()
                existing = row
        if existing is not None:
            bot = _decode(existing)
            return {"bot": bot, "spec": bot["spec"], "created": False, "reused": True}

        spec = build_spec(opp)
        _gaps = contract_gaps(spec)
        if _gaps:
            raise BotContractIncomplete(spec.get("id") or spec.get("bot_id"), _gaps)
        digest = spec_hash(spec)
        created_at = utcnow()
        cur = conn.execute(
            """INSERT INTO bot_specs
               (opportunity_id, job_id, spec_json, created_at, spec_hash, status, retired,
                retired_at, trigger)
               VALUES (?,?,?,?,?,'SPEC',0,NULL,?)""",
            (opp_id, job_id, canonical(spec), created_at, digest, trigger),
        )
        bot_id = cur.lastrowid
        conn.execute(
            "UPDATE opportunities SET updated_at = ? WHERE id = ?", (created_at, opp_id)
        )
        if write_audit:
            audit.record(
                COMPONENT_NAME, "bot.spec.created", "bot_spec", bot_id,
                {
                    "bot_id": bot_id,
                    "bot_name": spec["bot_name"],
                    "opportunity_id": opp_id,
                    "job_id": job_id,
                    "spec_version": SPEC_VERSION,
                    "spec_hash": digest,
                    "cost_usd": spec["estimated_monthly_cost_usd"],
                    "value_usd": spec["estimated_monthly_value_usd"],
                    "roi_ratio": spec["roi_ratio"],
                    "risk_level": spec["risk_level"],
                    "requires_human_approval": spec["requires_human_approval"],
                    "allowlist": spec["allowed_actions"],
                    "denylist": spec["denied_actions"],
                    "model_calls": 0,
                    "trigger": trigger,
                    "deployed": False,
                },
                conn=conn,
                legacy={
                    "job_id": job_id,
                    "kind": "bot_spec_created",
                    "from_state": sm.VERIFIED,
                    "to_state": sm.BOT_BUILT if job_id else None,
                    "note": (
                        f"GENERATED SPEC (not code, not a deployment): {spec['bot_name']} for "
                        f"opportunity {opp_id}; est. ${spec['estimated_monthly_cost_usd']:.2f}/mo "
                        f"cost vs ${spec['estimated_monthly_value_usd']:.2f}/mo value, ROI "
                        f"{spec['roi_ratio']}, risk {spec['risk_level']}, human approval "
                        f"{spec['requires_human_approval']}. spec_hash {digest[:12]}…"
                    ),
                    "data": {
                        "bot_id": bot_id,
                        "bot_name": spec["bot_name"],
                        "opportunity_id": opp_id,
                        "spec_hash": digest,
                        "risk_level": spec["risk_level"],
                        "requires_human_approval": spec["requires_human_approval"],
                        "deployed": False,
                    },
                },
            )
        row = conn.execute("SELECT * FROM bot_specs WHERE id = ?", (bot_id,)).fetchone()
        bot = _decode(row)
        return {"bot": bot, "spec": bot["spec"], "created": True, "reused": False}

    if ambient is not None:
        result = _work(ambient)
    else:
        with LOCK:
            conn = connect()
            try:
                result = _work(conn)
                conn.commit()
            except Exception:
                conn.rollback()
                raise
            finally:
                conn.close()
    log.info("bot factory: %s %s", "created" if result["created"] else "reused",
             result["spec"].get("bot_name"))
    return result



def _open_conn():
    """Open a connection using whatever helper this module already uses."""
    for name in ("_connect", "connect", "get_conn", "_conn", "open_conn"):
        fn = globals().get(name)
        if callable(fn):
            return fn()
    try:
        from . import db as _db
        for name in ("connect", "get_conn", "open_conn"):
            fn = getattr(_db, name, None)
            if callable(fn):
                return fn()
    except Exception:
        pass
    import sqlite3
    for name in ("DB_PATH", "DB", "DATABASE", "DB_FILE"):
        path = globals().get(name)
        if path:
            return sqlite3.connect(str(path))
    raise RuntimeError("no connection helper found — tell me the name")


def rewrite_spec(bot_id, spec, new_hash=None):
    """Replace a stored spec's JSON and hash together.

    The only correct way to change a stored spec: recompute the hash so
    hash_ok stays True. Editing spec_json alone desyncs the digest.
    """
    import json as _json
    if new_hash is None:
        new_hash = spec_hash(spec)
    conn = _open_conn()
    try:
        cols = [r[1] for r in conn.execute("PRAGMA table_info(bot_specs)")]
        json_col = next((c for c in ("spec_json", "spec", "json", "data", "body") if c in cols), None)
        hash_col = next((c for c in ("spec_hash", "hash", "digest") if c in cols), None)
        if not json_col or not hash_col:
            raise RuntimeError("bot_specs columns: %r" % (cols,))
        cur = conn.execute(
            "UPDATE bot_specs SET %s = ?, %s = ? WHERE id = ?" % (json_col, hash_col),
            (_json.dumps(spec, sort_keys=True), new_hash, bot_id),
        )
        conn.commit()
        if cur.rowcount != 1:
            raise KeyError("no bot_specs row with id %r" % (bot_id,))
    finally:
        conn.close()
    return new_hash


def list_specs(status: str | None = None, limit: int = 200) -> list[dict]:
    init_db()
    limit = max(1, min(int(limit), 1000))
    conn = connect()
    try:
        if status:
            rows = conn.execute(
                "SELECT * FROM bot_specs WHERE status = ? ORDER BY id DESC LIMIT ?",
                (status, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                "SELECT * FROM bot_specs ORDER BY id DESC LIMIT ?", (limit,)
            ).fetchall()
        return [_decode(r) for r in rows]
    finally:
        conn.close()


def get_spec(bot_id: int) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM bot_specs WHERE id = ?", (int(bot_id),)).fetchone()
        return _decode(row) if row else None
    finally:
        conn.close()


def find_spec_for_job(job_id: str) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute(
            "SELECT * FROM bot_specs WHERE job_id = ? ORDER BY id DESC LIMIT 1", (job_id,)
        ).fetchone()
        return _decode(row) if row else None
    finally:
        conn.close()


def find_spec_for_opportunity(opp_id: str) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute(
            "SELECT * FROM bot_specs WHERE opportunity_id = ? ORDER BY id DESC LIMIT 1", (opp_id,)
        ).fetchone()
        return _decode(row) if row else None
    finally:
        conn.close()


def set_status(bot_id: int, status: str, *, retire: bool = False, conn=None,
               reason: str = "") -> dict | None:
    """Record the outcome on the spec row. KILLED retires the bot; nothing is deleted."""
    owns = conn is None
    if owns:
        with LOCK:
            conn = connect()
    try:
        now = utcnow()
        conn.execute(
            "UPDATE bot_specs SET status = ?, retired = ?, retired_at = ? WHERE id = ?",
            (status, 1 if retire else 0, now if retire else None, int(bot_id)),
        )
        if retire:
            audit.record(
                COMPONENT_NAME, "bot.retired", "bot_spec", bot_id,
                {"bot_id": int(bot_id), "reason": reason,
                 "note": "retired, not deleted: the spec row and its hash are kept for audit"},
                conn=conn,
                legacy={
                    "job_id": None,
                    "kind": "bot_retired",
                    "from_state": None,
                    "to_state": sm.KILLED,
                    "note": f"bot {bot_id} retired: {reason}" if reason else f"bot {bot_id} retired",
                    "data": {"bot_id": int(bot_id), "deleted": False},
                },
            )
        if owns:
            conn.commit()
    finally:
        if owns:
            conn.close()
    return get_spec(bot_id)


def counts() -> dict:
    init_db()
    conn = connect()
    try:
        total = conn.execute("SELECT COUNT(*) AS n FROM bot_specs").fetchone()["n"]
        by_status = {
            r["status"]: r["n"]
            for r in conn.execute(
                "SELECT status, COUNT(*) AS n FROM bot_specs GROUP BY status"
            ).fetchall()
        }
        retired = conn.execute(
            "SELECT COUNT(*) AS n FROM bot_specs WHERE retired = 1"
        ).fetchone()["n"]
    finally:
        conn.close()
    return {"total": total, "by_status": by_status, "retired": retired,
            "spec_version": SPEC_VERSION}


# --------------------------------------------------------------------------
# The component (handles VERIFIED -> BOT_BUILT)
# --------------------------------------------------------------------------

class BotFactory:
    """Registered VERIFIED handler: build a deterministic spec or refuse with 409."""

    name = COMPONENT_NAME
    handles_state = sm.VERIFIED

    def __call__(self, job: dict) -> dict:
        return self.handle(job)

    def handle(self, job: dict) -> dict:
        payload = job.get("payload") or {}
        opp_id = payload.get("opportunity_id")
        if not opp_id:
            # Nothing to build from: a spec needs an opportunity's scores and verdict.
            # Refuse rather than invent a spec from a bare job title.
            raise BotBuildBlocked(
                f"bot factory refused {sm.VERIFIED} -> {sm.BOT_BUILT} for job "
                f"{str(job.get('id'))[:8]}: the job carries no opportunity_id, so there is no "
                f"VERIFIED opportunity to build from. Queue an opportunity first "
                f"(POST /opportunities/<id>/queue).",
                verdict=None,
                details={"job_id": job.get("id"), "opportunity_id": None},
            )

        result = build_bot(
            opp_id,
            trigger=f"job:{str(job.get('id', '?'))[:8]}",
            job_id=job.get("id"),
        )
        spec = result["spec"]
        bot = result["bot"]

        # The boundary check lives in the state machine and is repeated here, so a
        # patched component cannot build for an opportunity that is not VERIFIED.
        sm.assert_bot_build_gate(
            job.get("state"),
            sm.BOT_BUILT,
            verdict=(spec.get("opportunity") or {}).get("verdict"),
            opportunity_id=opp_id,
            job_id=job.get("id"),
        )

        note = (
            f"GENERATED SPEC (no code, no deployment): {spec['bot_name']} from opportunity "
            f"{opp_id}. est ${spec['estimated_monthly_cost_usd']:.2f}/mo cost vs "
            f"${spec['estimated_monthly_value_usd']:.2f}/mo value (ROI {spec['roi_ratio']}), "
            f"risk {spec['risk_level']}, human approval {spec['requires_human_approval']}. "
            f"spec_hash {bot['spec_hash'][:12]}…"
            + (" Reused the existing spec for this job." if result["reused"] else "")
        )
        return {
            "to_state": sm.BOT_BUILT,
            "note": note,
            "payload_patch": {
                "bot_id": bot["id"],
                "_bot_spec": {
                    "bot_id": bot["id"],
                    "bot_name": spec["bot_name"],
                    "spec_hash": bot["spec_hash"],
                    "risk_level": spec["risk_level"],
                    "requires_human_approval": spec["requires_human_approval"],
                    "estimated_monthly_cost_usd": spec["estimated_monthly_cost_usd"],
                    "estimated_monthly_value_usd": spec["estimated_monthly_value_usd"],
                    "roi_ratio": spec["roi_ratio"],
                    "deployed": False,
                },
            },
            "data": {"bot_id": bot["id"], "bot_name": spec["bot_name"],
                     "spec_hash": bot["spec_hash"], "reused": result["reused"],
                     "model_calls": 0, "deployed": False},
        }

    def describe(self) -> dict:
        return {
            "name": self.name,
            "handles_state": self.handles_state,
            "kind": "state",
            "description": "Deterministic bot-spec factory: allowlist, denylist, cost, value, "
                           "ROI and risk from published rules. No model, no deployment.",
            "spec_version": SPEC_VERSION,
        }


def register_bot_factory(registry: Registry) -> Component:
    """Register the factory as the VERIFIED handler, replacing BotFactoryStub."""
    factory = BotFactory()
    for stale in ("BotFactoryStub", COMPONENT_NAME):
        if registry.has(stale):
            registry.unregister(stale)
    return registry.register(
        Component(
            name=COMPONENT_NAME,
            handles_state=sm.VERIFIED,
            handler=factory,
            description=(
                "Deterministic bot-spec factory: builds an inspectable spec (allowlist, denylist, "
                "cost, value, ROI, risk) for a VERIFIED opportunity and refuses anything else "
                "with HTTP 409."
            ),
            produces_state=sm.BOT_BUILT,
        )
    )


def rules_document(bot_name: str | None = None) -> dict:
    """The inspectable model, served at GET /api/bots (documentation block)."""
    return {
        "component": COMPONENT_NAME,
        "spec_version": SPEC_VERSION,
        "model_calls": 0,
        "deterministic": True,
        "clock_in_scoring": False,
        "randomness": False,
        "spec_hash": "sha256(canonical_json(spec)) — canonical = json.dumps(sort_keys=True, separators=(',',':'))",
        "cost_model": {
            "version": COST_MODEL_VERSION,
            "formula": "runs_per_month * cost_per_run_usd + fixed_infra_usd",
            "cost_per_run_usd": f"{COST_PER_RUN_BASE_USD} + {COST_PER_STEP_USD} * step_count",
            "fixed_infra_usd": FIXED_INFRA_USD,
            "runs_per_month": RUNS_PER_MONTH,
            "default_runs_per_month": DEFAULT_RUNS_PER_MONTH,
        },
        "value_model": {
            "version": VALUE_MODEL_VERSION,
            "formula": "money_potential/100 * feasibility/100 * VALUE_CEILING_USD",
            "value_ceiling_usd": VALUE_CEILING_USD,
            "roi": "estimated_monthly_value_usd / estimated_monthly_cost_usd, rounded to 2dp",
        },
        "risk_model": {
            "version": RISK_MODEL_VERSION,
            "rule": ("high IF topic in HIGH_RISK_TOPICS OR feasibility < 60; ELSE medium IF "
                     "feasibility < 80 OR confidence < 60; ELSE low"),
            "high_risk_topics": list(HIGH_RISK_TOPICS),
            "requires_human_approval": (
                "true IF risk_level == high OR any step action is an outbound action adjacent to "
                "a denylisted outcome"
            ),
            "adjacent_actions": list(ADJACENT_ACTIONS),
        },
        "safety_boundary": {
            "allowlist_is_explicit": True,
            "denylist": list(DENYLIST),
            "rule": "a bot may call only allowlisted actions; denylisted actions are refused before dispatch",
        },
        "gate": (
            "A spec is only built for an opportunity whose stored verdict is VERIFIED. Enforced "
            "in the component AND at the state-machine boundary (verdict -> BOT_BUILT)."
        ),
        "honesty": HONESTY,
    }
