"""The OPPORTUNITY ENGINE — real, deterministic, rule-based.

What it does
------------
Reads the signals the ingestion layer already stored (``signals`` table), groups
them into explainable topic clusters by keyword overlap, and turns each cluster
into a scored OPPORTUNITY. Nothing is invented: every opportunity carries a
non-empty ``evidence`` list of ``{signal_id, source, url}`` pointing at rows that
actually exist in the signals table.

HARD RULE — NO UNCITED OPPORTUNITIES
------------------------------------
``validate_opportunity()`` is called on every candidate immediately before it is
written. If the evidence list is empty, or if any cited ``signal_id`` is not in
the store, the candidate is REJECTED: it is never inserted into
``opportunities``, the rejection is written to ``opportunity_rejections`` with a
reason, and an ``opportunity_rejected`` row is appended to the hash-chained audit
log. This is enforced in code, not by convention.

HONESTY RULE
------------
If the signal store is empty, or no topic cluster reaches ``MIN_CLUSTER_SIGNALS``,
the engine stores zero opportunities and says so in plain language (run note,
audit event, UI empty state). It never fabricates a business to fill the page.

Determinism
-----------
No randomness, no clock in the scores, no model call. Inputs are the stored
signals; outputs are a pure function of them. Same signals -> same scores.
"""

from __future__ import annotations

import hashlib
import json
import logging
import re
from datetime import datetime, timezone

from . import ingestion
from . import state_machine as sm
from . import audit
from .db import CURRENT_CONN, LOCK, connect, init_db
from .events import utcnow
from .registry import Component, Registry

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

ENGINE_NAME = "OpportunityEngine"

#: A cluster needs at least this many real signals to become an opportunity.
MIN_CLUSTER_SIGNALS = 2

#: How many evidence rows are attached to one opportunity (the whole cluster is
#: still recorded in ``cluster_signal_ids``).
MAX_EVIDENCE = 8

#: Statuses an opportunity can hold. No new pipeline states are introduced.
STATUS_NEW = "new"
STATUS_QUEUED = "queued"
STATUS_DISMISSED = "dismissed"
STATUSES = (STATUS_NEW, STATUS_QUEUED, STATUS_DISMISSED)


# --------------------------------------------------------------------------
# THE RULES — the single source of truth, exposed at GET /opportunities/rules
# --------------------------------------------------------------------------

COMPOSITE_WEIGHTS = {
    "signal_strength": 0.30,
    "money_potential": 0.30,
    "feasibility": 0.20,
    "confidence": 0.20,
}

RULES = {
    "version": "1.0",
    "deterministic": True,
    "model_calls": 0,
    "min_cluster_signals": MIN_CLUSTER_SIGNALS,
    "max_evidence": MAX_EVIDENCE,
    "clustering": {
        "method": "keyword/topic overlap on title+summary (lowercased, stopwords removed)",
        "rule": (
            "A signal joins a topic cluster when its normalised text contains at least one "
            "of the topic's keywords. A cluster becomes an opportunity only when it holds "
            ">= MIN_CLUSTER_SIGNALS distinct stored signals. Every cluster records the exact "
            "signal ids that formed it."
        ),
    },
    "scores": {
        "signal_strength": {
            "range": "0-100",
            "rule": (
                "min(100, 30 + 10*(cluster_size-1) + min(20, total_engagement//100) "
                "+ 10*distinct_sources)"
            ),
            "inputs": "cluster_size, total_engagement (sum of source scores), distinct_sources",
            "meaning": "how loud and how repeated the underlying signals are",
        },
        "money_potential": {
            "range": "0-100",
            "rule": "min(100, topic_money_base + 5*money_keyword_hits)  (money_keyword_hits capped at 5)",
            "inputs": "topic_money_base (per topic, see topics), money keyword hits in cluster text",
            "meaning": "how directly the cluster points at money changing hands",
        },
        "feasibility": {
            "range": "0-100",
            "rule": (
                "clamp(0, 100, topic_feasibility_base + 5*buildable_keyword_hits "
                "- 10*capital_intensive_hits)"
            ),
            "inputs": "topic_feasibility_base, buildable keywords (api/open source/tool/sdk), capital-intensive keywords (chip/fab/hardware/datacenter)",
            "meaning": "how plausibly a small AI-assisted team could ship this",
        },
        "confidence": {
            "range": "0-100",
            "rule": "min(100, 20 + 20*distinct_sources + 5*max(0, cluster_size-2))",
            "inputs": "distinct_sources, cluster_size",
            "meaning": "how independently corroborated the cluster is",
        },
    },
    "composite_score": {
        "range": "0-100",
        "rule": "round(0.30*signal_strength + 0.30*money_potential + 0.20*feasibility + 0.20*confidence)",
        "weights": COMPOSITE_WEIGHTS,
    },
    "citation_rule": (
        "An opportunity MUST cite >= 1 stored signal_id. Empty evidence, or evidence citing an "
        "id that is not in the signals table, is rejected and never stored."
    ),
    "honesty_rule": (
        "Empty signal store or no cluster >= MIN_CLUSTER_SIGNALS => zero opportunities and an "
        "explicit message. No placeholder or sample opportunities, ever."
    ),
}

#: Keyword -> topic taxonomy. Every topic maps to a concrete business shape and
#: the specific AI assistance that business needs.
TOPICS: list[dict] = [
    {
        "key": "ai-tooling",
        "label": "AI tooling",
        "keywords": ["ai", "llm", "gpt", "gemini", "model", "models", "agent", "agents",
                     "inference", "openai", "anthropic", "chatbot", "copilot", "prompt"],
        "business_type": "SaaS gap",
        "title": "Managed AI assistant layer for teams already paying for models",
        "what_they_need": (
            "An AI assistant that sits on top of the models these teams already buy: prompt "
            "routing, cost caps, evaluation, and a human review queue for outputs."
        ),
        "money_base": 70,
        "feasibility_base": 80,
    },
    {
        "key": "small-business-ops",
        "label": "Small-business operations",
        "keywords": ["small business", "smallbusiness", "hiring", "hire", "payroll", "invoice",
                     "bookkeeping", "accounting", "tax", "customer", "support", "tickets",
                     "scheduling", "booking", "admin"],
        "business_type": "local service",
        "title": "AI back-office clerk for owner-operated small businesses",
        "what_they_need": (
            "An AI clerk that reads inbound email/tickets, drafts replies, chases invoices and "
            "keeps the books tidy, with the owner approving anything that costs money."
        ),
        "money_base": 65,
        "feasibility_base": 85,
    },
    {
        "key": "commerce-payments",
        "label": "Commerce & payments",
        "keywords": ["stripe", "payments", "checkout", "ecommerce", "shopify", "marketplace",
                     "retail", "sales", "pricing", "subscription", "revenue", "ipo", "customer"],
        "business_type": "marketplace gap",
        "title": "AI pricing and listing assistant for small commerce sellers",
        "what_they_need": (
            "An AI assistant that rewrites listings, sets prices from competitor data and "
            "answers buyer questions, so a one-person shop competes with a merchandising team."
        ),
        "money_base": 75,
        "feasibility_base": 75,
    },
    {
        "key": "security-compliance",
        "label": "Security & compliance",
        "keywords": ["security", "breach", "rce", "vulnerability", "hack", "ransomware",
                     "privacy", "compliance", "gdpr", "outage", "sued", "lawsuit",
                     "investigation", "spy", "attack"],
        "business_type": "SaaS gap",
        "title": "AI incident-triage and disclosure assistant for small engineering teams",
        "what_they_need": (
            "An AI assistant that turns advisories, CVEs and outage reports into a prioritised "
            "patch list with customer-facing disclosure drafts."
        ),
        "money_base": 80,
        "feasibility_base": 70,
    },
    {
        "key": "chips-hardware",
        "label": "Chips & infrastructure",
        "keywords": ["nvidia", "chip", "chips", "gpu", "semiconductor", "hardware",
                     "datacenter", "fab", "inference"],
        "business_type": "content/trend play",
        "title": "AI supply-chain briefing service for chip and infrastructure buyers",
        "what_they_need": (
            "An AI analyst that tracks supplier, export-control and capacity news and sends a "
            "short weekly risk brief with sourced citations."
        ),
        "money_base": 60,
        "feasibility_base": 55,
    },
    {
        "key": "dev-tools",
        "label": "Developer tooling",
        "keywords": ["rust", "compiler", "open source", "github", "api", "sdk", "framework",
                     "developer", "programming", "code", "jquery", "emacs", "curl", "nim"],
        "business_type": "SaaS gap",
        "title": "AI migration assistant for teams stuck on ageing dependencies",
        "what_they_need": (
            "An AI assistant that reads release notes and changelogs, flags breaking changes in "
            "a repo and opens the upgrade PR with tests."
        ),
        "money_base": 65,
        "feasibility_base": 85,
    },
    {
        "key": "content-media",
        "label": "Content & media",
        "keywords": ["content", "video", "streaming", "creator", "podcast", "newsletter",
                     "seo", "search traffic", "marketing", "ads", "media"],
        "business_type": "content/trend play",
        "title": "AI repurposing desk for independent publishers losing search traffic",
        "what_they_need": (
            "An AI desk that turns one article into channel-specific drafts and tracks what "
            "actually earns attention, with every claim linked to the source."
        ),
        "money_base": 55,
        "feasibility_base": 90,
    },
    {
        "key": "housing-local",
        "label": "Housing & local services",
        "keywords": ["house", "housing", "rent", "mortgage", "property", "landlord",
                     "buy a house", "tenants"],
        "business_type": "local service",
        "title": "AI paperwork assistant for small landlords and first-time buyers",
        "what_they_need": (
            "An AI assistant that reads tenancy and mortgage paperwork, extracts deadlines and "
            "drafts the letters, with a human signing off."
        ),
        "money_base": 60,
        "feasibility_base": 80,
    },
    {
        "key": "jobs-labour",
        "label": "Jobs & labour",
        "keywords": ["jobs", "job", "unemployment", "wage", "wages", "workers", "labour",
                     "labor", "under-25", "hiring", "hire", "recruit", "career"],
        "business_type": "marketplace gap",
        "title": "AI hiring copilot for firms that say they cannot afford to hire",
        "what_they_need": (
            "An AI copilot that writes role specs, screens applications against explicit "
            "criteria and schedules interviews, so a small firm hires without a recruiter."
        ),
        "money_base": 70,
        "feasibility_base": 80,
    },
    {
        "key": "mobility-logistics",
        "label": "Mobility & logistics",
        "keywords": ["waymo", "delivery", "logistics", "fleet", "transport", "shipping",
                     "rides", "drivers", "freight"],
        "business_type": "local service",
        "title": "AI dispatch assistant for small delivery and transport fleets",
        "what_they_need": (
            "An AI dispatcher that reads incoming orders, sequences routes and messages drivers "
            "and customers, escalating exceptions to a human."
        ),
        "money_base": 65,
        "feasibility_base": 65,
    },
]

MONEY_KEYWORDS = ["raises", "raised", "revenue", "funding", "ipo", "billion", "million",
                  "pricing", "cost", "sales", "profit", "investigat", "sued", "fine"]
BUILDABLE_KEYWORDS = ["api", "open source", "tool", "sdk", "framework", "library", "plugin"]
CAPITAL_INTENSIVE_KEYWORDS = ["chip", "fab", "hardware", "datacenter", "gpu", "semiconductor"]

STOPWORDS = {
    "the", "a", "an", "and", "or", "of", "to", "in", "on", "for", "with", "as", "at", "by",
    "from", "is", "are", "was", "were", "be", "been", "it", "its", "this", "that", "these",
    "those", "his", "her", "their", "he", "she", "they", "we", "you", "i", "not", "no", "but",
    "after", "before", "over", "into", "than", "then", "so", "if", "will", "would", "can",
    "could", "has", "have", "had", "do", "does", "did", "how", "what", "why", "who", "when",
    "where", "says", "said", "new", "up", "out", "about", "more", "most", "just", "now",
}


# --------------------------------------------------------------------------
# Errors
# --------------------------------------------------------------------------

class UncitedOpportunity(Exception):
    """Raised when a candidate cannot cite at least one real stored signal."""

    def __init__(self, reason: str, candidate: dict | None = None):
        super().__init__(reason)
        self.reason = reason
        self.candidate = candidate or {}


# --------------------------------------------------------------------------
# Text helpers
# --------------------------------------------------------------------------

def _norm(text: str) -> str:
    return re.sub(r"\s+", " ", (text or "").lower()).strip()


def _tokens(text: str) -> list[str]:
    return [t for t in re.findall(r"[a-z0-9$][a-z0-9$'\-]*", _norm(text)) if t not in STOPWORDS]


def _signal_text(sig: dict) -> str:
    return _norm(f"{sig.get('title', '')} {sig.get('summary', '')}")


def _hits(text: str, keywords: list[str]) -> int:
    """Count keyword hits; multi-word keywords match as substrings, single words as words."""
    n = 0
    for kw in keywords:
        kw = kw.lower()
        if " " in kw or "-" in kw:
            if kw in text:
                n += 1
        elif re.search(rf"(?<![a-z0-9]){re.escape(kw)}(?![a-z0-9])", text):
            n += 1
    return n


def _topic_for(sig: dict) -> dict | None:
    """The topic with the MOST keyword hits in the signal text.

    Ties are broken by declared topic order, so the assignment is deterministic.
    A signal that matches no topic keyword returns None and is never forced into
    a cluster (it is reported as ``unclustered``).
    """
    text = _signal_text(sig)
    best, best_hits = None, 0
    for topic in TOPICS:
        hits = _hits(text, topic["keywords"])
        if hits > best_hits:
            best, best_hits = topic, hits
    return best


# --------------------------------------------------------------------------
# 1. Clustering
# --------------------------------------------------------------------------

def cluster_signals(signals: list[dict]) -> list[dict]:
    """Group stored signals by topic keyword overlap.

    Returns clusters sorted by (size desc, key asc) so the output is stable:
        {key, label, topic, signal_ids, sources, size}
    Signals that match no topic are left out of every cluster (they are counted
    as ``unclustered`` by the caller) — they are never forced into an opportunity.
    """
    buckets: dict[str, list[dict]] = {}
    for sig in signals:
        topic = _topic_for(sig)
        if topic is None:
            continue
        buckets.setdefault(topic["key"], []).append(sig)

    clusters = []
    for key, members in buckets.items():
        topic = next(t for t in TOPICS if t["key"] == key)
        members = sorted(members, key=lambda s: (s.get("source", ""), s.get("id", "")))
        clusters.append(
            {
                "key": key,
                "label": topic["label"],
                "topic": topic,
                "signal_ids": [m["id"] for m in members],
                "sources": sorted({m.get("source", "") for m in members}),
                "size": len(members),
            }
        )
    clusters.sort(key=lambda c: (-c["size"], c["key"]))
    return clusters


# --------------------------------------------------------------------------
# 2. Scoring — pure functions of the cluster, fully documented
# --------------------------------------------------------------------------

def score_cluster(cluster: dict, signals_by_id: dict[str, dict]) -> dict:
    """Return the four 0-100 sub-scores, each with the rule and inputs that made it."""
    members = [signals_by_id[i] for i in cluster["signal_ids"] if i in signals_by_id]
    size = len(members)
    sources = sorted({m.get("source", "") for m in members})
    distinct_sources = len(sources)
    engagement = sum(int(m.get("score") or 0) for m in members)
    text = " ".join(_signal_text(m) for m in members)
    topic = cluster["topic"]

    # -- signal_strength ---------------------------------------------------
    ss = 30 + 10 * max(0, size - 1) + min(20, engagement // 100) + 10 * distinct_sources
    ss_raw = ss
    ss = max(0, min(100, ss))
    signal_strength = {
        "value": ss,
        "rule": RULES["scores"]["signal_strength"]["rule"],
        "inputs": {
            "cluster_size": size,
            "total_engagement": engagement,
            "distinct_sources": distinct_sources,
        },
        "working": (
            f"30 + 10*({size}-1) + min(20, {engagement}//100) + 10*{distinct_sources} "
            f"= {ss_raw} -> {ss}"
        ),
    }

    # -- money_potential ---------------------------------------------------
    money_hits = min(5, _hits(text, MONEY_KEYWORDS))
    mp_raw = topic["money_base"] + 5 * money_hits
    mp = max(0, min(100, mp_raw))
    money_potential = {
        "value": mp,
        "rule": RULES["scores"]["money_potential"]["rule"],
        "inputs": {
            "topic_money_base": topic["money_base"],
            "money_keyword_hits": money_hits,
            "money_keywords": MONEY_KEYWORDS,
        },
        "working": f"{topic['money_base']} + 5*{money_hits} = {mp_raw} -> {mp}",
    }

    # -- feasibility -------------------------------------------------------
    buildable = _hits(text, BUILDABLE_KEYWORDS)
    capital = _hits(text, CAPITAL_INTENSIVE_KEYWORDS)
    feas_raw = topic["feasibility_base"] + 5 * buildable - 10 * capital
    feas = max(0, min(100, feas_raw))
    feasibility = {
        "value": feas,
        "rule": RULES["scores"]["feasibility"]["rule"],
        "inputs": {
            "topic_feasibility_base": topic["feasibility_base"],
            "buildable_keyword_hits": buildable,
            "capital_intensive_hits": capital,
        },
        "working": (
            f"{topic['feasibility_base']} + 5*{buildable} - 10*{capital} = {feas_raw} -> {feas}"
        ),
    }

    # -- confidence --------------------------------------------------------
    conf_raw = 20 + 20 * distinct_sources + 5 * max(0, size - 2)
    conf = max(0, min(100, conf_raw))
    confidence = {
        "value": conf,
        "rule": RULES["scores"]["confidence"]["rule"],
        "inputs": {"distinct_sources": distinct_sources, "cluster_size": size},
        "working": f"20 + 20*{distinct_sources} + 5*max(0,{size}-2) = {conf_raw} -> {conf}",
    }

    return {
        "signal_strength": signal_strength,
        "money_potential": money_potential,
        "feasibility": feasibility,
        "confidence": confidence,
    }


def composite_score(scores: dict) -> int:
    """Documented weighted combination of the four sub-scores."""
    total = sum(COMPOSITE_WEIGHTS[k] * scores[k]["value"] for k in COMPOSITE_WEIGHTS)
    return int(round(total))


# --------------------------------------------------------------------------
# 3. Candidate construction + the hard citation gate
# --------------------------------------------------------------------------

def _evidence_for(cluster: dict, signals_by_id: dict[str, dict]) -> list[dict]:
    """Build evidence rows from signals that ACTUALLY exist in the store."""
    rows = []
    for sid in cluster["signal_ids"]:
        sig = signals_by_id.get(sid)
        if sig is None:
            continue
        rows.append(
            {
                "signal_id": sig["id"],
                "source": sig.get("source", ""),
                "url": sig.get("url", ""),
                "title": sig.get("title", ""),
            }
        )
    rows.sort(key=lambda r: (r["source"], r["signal_id"]))
    return rows[:MAX_EVIDENCE]


def validate_opportunity(opp: dict, known_signal_ids: set[str]) -> None:
    """THE HARD RULE. Raise UncitedOpportunity unless every citation is real.

    Checks:
      1. evidence is a non-empty list
      2. every evidence row has a signal_id
      3. every cited signal_id exists in the signals table right now
    """
    evidence = opp.get("evidence")
    if not isinstance(evidence, list) or not evidence:
        raise UncitedOpportunity(
            "no evidence: opportunity cites zero stored signals", candidate=opp
        )
    for row in evidence:
        sid = (row or {}).get("signal_id")
        if not sid:
            raise UncitedOpportunity(
                "evidence row without a signal_id", candidate=opp
            )
        if sid not in known_signal_ids:
            raise UncitedOpportunity(
                f"cited signal_id {sid!r} is not in the signals store", candidate=opp
            )


def build_opportunity(cluster: dict, signals_by_id: dict[str, dict],
                      claims: list[dict] | None = None) -> dict:
    """Turn one cluster into a scored opportunity. Raises if it cannot be cited.

    ``claims`` is OPTIONAL and defaults to ``None``. With ``None`` the returned
    opportunity is exactly what it has always been — the same keys, the same
    order, byte-for-byte identical JSON — so every existing caller and test is
    untouched.

    When a list is passed (the live-data bridge in ``orchestrator/live_ingest.py``
    is the only caller), each entry is attached under ``opp["claims"]`` after the
    same citation rule the claim store enforces: a claim without a non-empty
    ``text``, ``source_url`` AND ``source_turn`` is refused here too, so an
    uncitable claim never reaches the writer.
    """
    evidence = _evidence_for(cluster, signals_by_id)
    scores = score_cluster(cluster, signals_by_id)
    topic = cluster["topic"]
    opp = {
        "id": opportunity_id(cluster["key"], cluster["signal_ids"]),
        "title": topic["title"],
        "business_type": topic["business_type"],
        "what_they_need": topic["what_they_need"],
        "evidence": evidence,
        "scores": scores,
        "composite_score": composite_score(scores),
        "status": STATUS_NEW,
        "cluster_key": cluster["key"],
        "cluster_label": cluster["label"],
        "cluster_signal_ids": list(cluster["signal_ids"]),
        "cluster_size": cluster["size"],
        "sources": list(cluster["sources"]),
    }
    # Gate BEFORE anything can be stored.
    validate_opportunity(opp, set(signals_by_id))
    if claims is not None:
        # OPTIONAL claims (default None keeps the shape above untouched).
        opp["claims"] = _validated_claims(claims, opp)
    return opp


def _validated_claims(claims: list[dict], opp: dict) -> list[dict]:
    """Attach-only path for optional claims. Same citation rule as the store."""
    if not isinstance(claims, list):
        raise UncitedOpportunity(
            "claims must be a list of {text, source_url, source_turn} rows",
            candidate=opp,
        )
    out = []
    for claim in claims:
        row = dict(claim) if isinstance(claim, dict) else {"text": str(claim)}
        text = str(row.get("text") or "").strip()
        if not text:
            raise UncitedOpportunity("claim without text", candidate=opp)
        if not str(row.get("source_url") or "").strip():
            raise UncitedOpportunity(
                f"claim {text[:60]!r} has no source_url — no citation, no claim",
                candidate=opp,
            )
        if not str(row.get("source_turn") or "").strip():
            raise UncitedOpportunity(
                f"claim {text[:60]!r} has no source_turn — no citation, no claim",
                candidate=opp,
            )
        row["text"] = text
        out.append(row)
    return out


def opportunity_id(cluster_key: str, signal_ids: list[str]) -> str:
    """Stable id: same cluster + same signals => same id (idempotent re-runs)."""
    key = f"{cluster_key}|{','.join(sorted(signal_ids))}"
    return hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]


# --------------------------------------------------------------------------
# 4. Persistence
# --------------------------------------------------------------------------

def _row_to_opportunity(row) -> dict:
    d = dict(row)
    for field in ("evidence", "scores", "cluster_signal_ids", "sources"):
        try:
            d[field] = json.loads(d.get(field) or "[]")
        except (ValueError, TypeError):
            d[field] = [] if field != "scores" else {}
    return d


def list_opportunities(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 opportunities WHERE status = ? "
                "ORDER BY composite_score DESC, id ASC LIMIT ?",
                (status, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                "SELECT * FROM opportunities ORDER BY composite_score DESC, id ASC LIMIT ?",
                (limit,),
            ).fetchall()
        return [_row_to_opportunity(r) for r in rows]
    finally:
        conn.close()


def get_opportunity(opp_id: str) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM opportunities WHERE id = ?", (opp_id,)).fetchone()
        return _row_to_opportunity(row) if row else None
    finally:
        conn.close()


def list_runs(limit: int = 10) -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM opportunity_runs ORDER BY id DESC LIMIT ?", (max(1, int(limit)),)
        ).fetchall()
        out = []
        for r in rows:
            d = dict(r)
            for f in ("rejections", "cluster_summary"):
                try:
                    d[f] = json.loads(d.get(f) or "[]")
                except (ValueError, TypeError):
                    d[f] = []
            out.append(d)
        return out
    finally:
        conn.close()


def list_rejections(limit: int = 50) -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM opportunity_rejections ORDER BY id DESC LIMIT ?", (max(1, int(limit)),)
        ).fetchall()
        out = []
        for r in rows:
            d = dict(r)
            try:
                d["candidate"] = json.loads(d.get("candidate") or "{}")
            except (ValueError, TypeError):
                d["candidate"] = {}
            out.append(d)
        return out
    finally:
        conn.close()


def counts() -> dict:
    init_db()
    conn = connect()
    try:
        total = conn.execute("SELECT COUNT(*) AS n FROM opportunities").fetchone()["n"]
        by_status = {
            r["status"]: r["n"]
            for r in conn.execute(
                "SELECT status, COUNT(*) AS n FROM opportunities GROUP BY status"
            ).fetchall()
        }
        rejected = conn.execute("SELECT COUNT(*) AS n FROM opportunity_rejections").fetchone()["n"]
        last = conn.execute(
            "SELECT * FROM opportunity_runs ORDER BY id DESC LIMIT 1"
        ).fetchone()
    finally:
        conn.close()
    last_run = None
    if last:
        last_run = dict(last)
        for f in ("rejections", "cluster_summary"):
            try:
                last_run[f] = json.loads(last_run.get(f) or "[]")
            except (ValueError, TypeError):
                last_run[f] = []
    return {
        "total": total,
        "by_status": by_status,
        "rejected_total": rejected,
        "last_run": last_run,
    }


# --------------------------------------------------------------------------
# 5. The run
# --------------------------------------------------------------------------

def run_engine(limit: int = 500, actor: str = ENGINE_NAME) -> dict:
    """Read stored signals -> cluster -> score -> store. Deterministic and idempotent.

    Returns a run record with the real counts:
        signals_read, clusters, produced, created, updated, rejected, message
    """
    init_db()
    signals = ingestion.list_signals(limit=limit)
    signals_by_id = {s["id"]: s for s in signals}
    clusters = cluster_signals(signals)
    eligible = [c for c in clusters if c["size"] >= MIN_CLUSTER_SIGNALS]
    unclustered = sum(1 for s in signals if _topic_for(s) is None)

    produced: list[dict] = []
    rejections: list[dict] = []

    for cluster in eligible:
        try:
            opp = build_opportunity(cluster, signals_by_id)
            # Defence in depth: re-check the hard rule at the persistence
            # boundary, so no code path can store an uncited opportunity even if
            # the builder is replaced or patched.
            validate_opportunity(opp, set(signals_by_id))
        except UncitedOpportunity as exc:
            rejections.append(
                {
                    "cluster_key": cluster["key"],
                    "cluster_label": cluster["label"],
                    "cluster_signal_ids": cluster["signal_ids"],
                    "reason": exc.reason,
                }
            )
            continue
        produced.append(opp)

    # Honest message when there is nothing real to work with.
    if not signals:
        message = (
            "0 real signals in the store. The engine produced 0 opportunities and invented "
            "none. Fetch signals first (Senses -> Fetch now), then run the engine again."
        )
    elif not eligible:
        message = (
            f"{len(signals)} real signal(s) read, but no topic cluster reached the minimum of "
            f"{MIN_CLUSTER_SIGNALS} signals, so 0 opportunities were formed. Nothing was "
            f"invented to fill the gap."
        )
    else:
        message = (
            f"{len(signals)} real signal(s) read -> {len(clusters)} topic cluster(s), "
            f"{len(eligible)} large enough to score -> {len(produced)} opportunity(ies) stored, "
            f"{len(rejections)} rejected for lack of citations."
        )

    now = utcnow()
    with LOCK:
        conn = connect()
        try:
            cur = conn.execute(
                """INSERT INTO opportunity_runs
                   (started_at, finished_at, signals_read, clusters, eligible_clusters,
                    produced, created, updated, rejected, unclustered, message, rejections,
                    cluster_summary, trigger)
                   VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (now, now, len(signals), len(clusters), len(eligible), len(produced), 0, 0,
                 len(rejections), unclustered, message, "[]", "[]", actor),
            )
            run_id = cur.lastrowid
            created = updated = 0
            for opp in produced:
                existing = conn.execute(
                    "SELECT id, status, job_id FROM opportunities WHERE id = ?", (opp["id"],)
                ).fetchone()
                if existing:
                    conn.execute(
                        """UPDATE opportunities SET title=?, business_type=?, what_they_need=?,
                           evidence=?, scores=?, composite_score=?, cluster_key=?, cluster_label=?,
                           cluster_signal_ids=?, cluster_size=?, sources=?, run_id=?, updated_at=?
                           WHERE id=?""",
                        (opp["title"], opp["business_type"], opp["what_they_need"],
                         json.dumps(opp["evidence"], sort_keys=True),
                         json.dumps(opp["scores"], sort_keys=True), opp["composite_score"],
                         opp["cluster_key"], opp["cluster_label"],
                         json.dumps(opp["cluster_signal_ids"]), opp["cluster_size"],
                         json.dumps(opp["sources"]), run_id, now, opp["id"]),
                    )
                    updated += 1
                else:
                    conn.execute(
                        """INSERT INTO opportunities
                           (id, title, business_type, what_they_need, evidence, scores,
                            composite_score, status, cluster_key, cluster_label,
                            cluster_signal_ids, cluster_size, sources, run_id, job_id,
                            created_at, updated_at)
                           VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                        (opp["id"], opp["title"], opp["business_type"], opp["what_they_need"],
                         json.dumps(opp["evidence"], sort_keys=True),
                         json.dumps(opp["scores"], sort_keys=True), opp["composite_score"],
                         STATUS_NEW, opp["cluster_key"], opp["cluster_label"],
                         json.dumps(opp["cluster_signal_ids"]), opp["cluster_size"],
                         json.dumps(opp["sources"]), run_id, None, now, now),
                    )
                    created += 1

            for rej in rejections:
                conn.execute(
                    """INSERT INTO opportunity_rejections
                       (ts, run_id, cluster_key, cluster_label, reason, candidate)
                       VALUES (?,?,?,?,?,?)""",
                    (now, run_id, rej["cluster_key"], rej["cluster_label"], rej["reason"],
                     json.dumps(rej, sort_keys=True)),
                )
                audit.record(
                    actor, "opportunity.rejected", "opportunity_candidate", rej["cluster_key"],
                    {"run_id": run_id, "reason": rej["reason"],
                     "cluster_label": rej["cluster_label"],
                     "signal_ids": rej["cluster_signal_ids"]},
                    conn=conn,
                    legacy={
                        "job_id": None,
                        "kind": "opportunity_rejected",
                        "from_state": None,
                        "to_state": None,
                        "note": (
                            f"REJECTED opportunity candidate from cluster "
                            f"{rej['cluster_key']!r}: {rej['reason']}. Not stored."
                        ),
                        "data": rej,
                    },
                )

            cluster_summary = [
                {"key": c["key"], "label": c["label"], "size": c["size"],
                 "signal_ids": c["signal_ids"], "sources": c["sources"]}
                for c in clusters
            ]
            conn.execute(
                """UPDATE opportunity_runs SET created=?, updated=?, rejections=?,
                   cluster_summary=? WHERE id=?""",
                (created, updated, json.dumps(rejections, sort_keys=True),
                 json.dumps(cluster_summary, sort_keys=True), run_id),
            )
            audit.record(
                actor, "opportunity.run", "opportunity_run", run_id,
                {
                    "signals_read": len(signals), "clusters": len(clusters),
                    "eligible_clusters": len(eligible), "produced": len(produced),
                    "created": created, "updated": updated, "rejected": len(rejections),
                    "unclustered": unclustered, "message": message,
                },
                conn=conn,
                legacy={
                    "job_id": None,
                    "kind": "opportunity_run",
                    "from_state": None,
                    "to_state": None,
                    "note": f"OPPORTUNITY ENGINE: {message}",
                    "data": {
                        "run_id": run_id,
                        "signals_read": len(signals),
                        "clusters": len(clusters),
                        "eligible_clusters": len(eligible),
                        "produced": len(produced),
                        "created": created,
                        "updated": updated,
                        "rejected": len(rejections),
                        "unclustered": unclustered,
                        "opportunity_ids": [o["id"] for o in produced],
                    },
                },
            )
            for opp in produced:
                audit.record(
                    actor, "opportunity.created", "opportunity", opp["id"],
                    {
                        "run_id": run_id,
                        "title": opp["title"],
                        "business_type": opp["business_type"],
                        "composite_score": opp["composite_score"],
                        "cluster_key": opp["cluster_key"],
                        "evidence_signal_ids": [e["signal_id"] for e in opp["evidence"]],
                    },
                    conn=conn,
                )
            conn.commit()
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()

    log.info("[%s] %s", actor, message)
    return {
        "id": run_id,
        "started_at": now,
        "finished_at": now,
        "signals_read": len(signals),
        "clusters": len(clusters),
        "eligible_clusters": len(eligible),
        "produced": len(produced),
        "created": created,
        "updated": updated,
        "rejected": len(rejections),
        "unclustered": unclustered,
        "message": message,
        "rejections": rejections,
        "cluster_summary": cluster_summary,
        "opportunities": produced,
    }


# --------------------------------------------------------------------------
# 6. Wire into the loop: opportunity -> job at INGESTED (no new states)
# --------------------------------------------------------------------------

def opportunity_to_job(opp_id: str, registry: Registry | None = None) -> dict:
    """Create a job from an opportunity. It enters at INGESTED via the normal intake.

    No new states, no bypass of the transition table: the job is created exactly
    like any other job and must advance INGESTED -> VERIFIED -> ... normally.
    """
    from . import service  # local import: service imports the registry, avoid a cycle

    opp = get_opportunity(opp_id)
    if opp is None:
        raise ValueError(f"no opportunity with id {opp_id!r}")
    if opp.get("job_id"):
        job = service.get_job(opp["job_id"])
        return {"opportunity": opp, "job": job, "created": False}

    payload = {
        "opportunity_id": opp["id"],
        "business_type": opp["business_type"],
        "what_they_need": opp["what_they_need"],
        "composite_score": opp["composite_score"],
        "scores": {k: v["value"] for k, v in opp["scores"].items()},
        "evidence": opp["evidence"],
        "cluster_key": opp["cluster_key"],
    }
    job = service.create_job(
        title=opp["title"],
        source=f"opportunity/{opp['id']}",
        payload=payload,
        registry=registry,
    )
    with LOCK:
        conn = connect()
        try:
            conn.execute(
                "UPDATE opportunities SET status=?, job_id=?, updated_at=? WHERE id=?",
                (STATUS_QUEUED, job["id"], utcnow(), opp["id"]),
            )
            audit.record(
                ENGINE_NAME, "opportunity.queued", "opportunity", opp["id"],
                {"job_id": job["id"], "composite_score": opp["composite_score"],
                 "status": STATUS_QUEUED, "evidence_count": len(opp["evidence"])},
                conn=conn,
                legacy={
                    "job_id": job["id"],
                    "kind": "opportunity_queued",
                    "from_state": None,
                    "to_state": sm.INGESTED,
                    "note": (
                        f"opportunity {opp['id']} ({opp['cluster_key']}, composite "
                        f"{opp['composite_score']}) turned into a job; it enters the pipeline at "
                        f"INGESTED and must advance through the normal transition table"
                    ),
                    "data": {"opportunity_id": opp["id"],
                             "evidence_count": len(opp["evidence"])},
                },
            )
            conn.commit()
        except Exception:
            conn.rollback()
            raise
        finally:
            conn.close()
    return {"opportunity": get_opportunity(opp_id), "job": job, "created": True}


# --------------------------------------------------------------------------
# 7. Registry component (a TOOL, not a pipeline state)
# --------------------------------------------------------------------------

class OpportunityEngine:
    """Registered capability. Not a pipeline state — it is looked up by name."""

    name = ENGINE_NAME

    def __call__(self, job: dict | None = None) -> dict:
        return self.handle(job or {})

    def handle(self, job: dict) -> dict:
        run = run_engine()
        note = f"REAL OPPORTUNITY ENGINE: {run['message']}"
        return {
            "to_state": None,  # a tool never transitions a job
            "note": note,
            "payload_patch": {},
            "data": {
                "run_id": run["id"],
                "signals_read": run["signals_read"],
                "produced": run["produced"],
                "rejected": run["rejected"],
            },
        }


def register_opportunity_engine(registry: Registry) -> Component:
    """Register the engine as a tool component. Idempotent."""
    if registry.has(ENGINE_NAME):
        return registry.get(ENGINE_NAME)
    return registry.register(
        Component(
            name=ENGINE_NAME,
            handles_state=None,
            handler=OpportunityEngine(),
            description=(
                "REAL opportunity engine: clusters stored signals by topic, scores them with "
                "documented rules, rejects any candidate that cannot cite a stored signal."
            ),
            kind="tool",
        )
    )


def rules_document() -> dict:
    """The inspectable rule set, served at GET /opportunities/rules."""
    return {
        "engine": ENGINE_NAME,
        "rules": RULES,
        "topics": [
            {
                "key": t["key"],
                "label": t["label"],
                "keywords": t["keywords"],
                "business_type": t["business_type"],
                "title": t["title"],
                "what_they_need": t["what_they_need"],
                "money_base": t["money_base"],
                "feasibility_base": t["feasibility_base"],
            }
            for t in TOPICS
        ],
        "money_keywords": MONEY_KEYWORDS,
        "buildable_keywords": BUILDABLE_KEYWORDS,
        "capital_intensive_keywords": CAPITAL_INTENSIVE_KEYWORDS,
        "statuses": list(STATUSES),
    }
