"""THE MEMORY STORE — durable, file-backed, citation-enforced.

What this is
------------
A second SQLite file (``data/jarvis.db`` by default, override with
``JARVIS_MEMORY_DB``) that holds the part of JARVIS that has to survive a
restart *and* survive an audit:

    opportunities   what was noticed, and where it was found
    claims          the individual assertions behind an opportunity
    decisions       keep/kill, tagged with the rule version that decided it
    outcomes        the measured number after the bet was made
    rule_versions   the published rule history, with precision/recall

Why a separate file
-------------------
The orchestration DB (``jarvis.db`` in the repo root) holds the operational
pipeline: jobs, events, signals, verification runs. The memory store is the
long-term record of what was concluded. Keeping them apart means the memory
file is a small, self-contained artefact you can inspect, back up or hand to
someone else without dragging the event log along.

HARD RULE — NO CLAIM WITHOUT A CITATION
---------------------------------------
Every claim needs BOTH a ``source_url`` and a ``source_turn``. This is enforced
in three places, so no code path can bypass it:

    1. the columns are ``NOT NULL`` and carry ``CHECK (length(trim(...)) > 0)``
    2. ``validate_citation()`` runs in the insert path before any SQL
    3. ``create_claim()`` is the only function that writes to ``claims``

A missing or blank citation raises ``CitationError`` (HTTP 400,
code ``citation_required``) and nothing is written. There is no "unknown" or
"n/a" escape hatch: a claim you cannot cite is a claim you do not get to keep.
"""

from __future__ import annotations

import os
import sqlite3
import threading
from datetime import datetime, timezone

from . import audit
from .errors import OrchestratorError, ValidationError

COMPONENT_NAME = "MemoryStore"

#: Rule versions published by the sample/seed bundle. Real versions may be
#: published later via ``POST /api/memory/rules``.
SEED_RULES = [
    {
        "version": "v0.1.0",
        "description": "Baseline: keep anything with >=2 independent citations and a named buyer.",
        "precision": 0.41,
        "recall": 0.88,
        "published_at": "2026-09-02T09:00:00Z",
    },
    {
        "version": "v0.2.0",
        "description": "Adds the pain-recurrence rule (same complaint in >=3 sources) and a pricing sanity check.",
        "precision": 0.63,
        "recall": 0.74,
        "published_at": "2026-10-06T09:00:00Z",
    },
    {
        "version": "v0.3.0",
        "description": "Adds reachability check on every cited URL; kills opportunities whose sources no longer resolve.",
        "precision": 0.79,
        "recall": 0.66,
        "published_at": "2026-11-10T09:00:00Z",
    },
]

#: Sample prefix. Rows whose id starts with this are seed data and are labelled
#: as such in the UI — the schema itself stays exactly as specified.
SAMPLE_PREFIX = "sample-"

LOCK = threading.RLock()

DEFAULT_DB = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "jarvis.db"
)

SCHEMA = """
PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS opportunities (
    id          TEXT PRIMARY KEY,
    title       TEXT NOT NULL,
    source_url  TEXT NOT NULL,
    found_at    TEXT NOT NULL,
    status      TEXT NOT NULL DEFAULT 'open'
);

CREATE TABLE IF NOT EXISTS claims (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    opportunity_id  TEXT NOT NULL REFERENCES opportunities(id),
    text            TEXT NOT NULL,
    source_url      TEXT NOT NULL CHECK (length(trim(source_url)) > 0),
    source_turn     TEXT NOT NULL CHECK (length(trim(source_turn)) > 0),
    captured_at     TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS decisions (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    opportunity_id  TEXT NOT NULL REFERENCES opportunities(id),
    verdict         TEXT NOT NULL CHECK (verdict IN ('keep','kill')),
    rule_version    TEXT NOT NULL REFERENCES rule_versions(version),
    rationale       TEXT NOT NULL DEFAULT '',
    decided_at      TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS outcomes (
    id              INTEGER PRIMARY KEY AUTOINCREMENT,
    opportunity_id  TEXT NOT NULL REFERENCES opportunities(id),
    metric          TEXT NOT NULL,
    value           REAL NOT NULL,
    measured_at     TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS rule_versions (
    version       TEXT PRIMARY KEY,
    description   TEXT NOT NULL DEFAULT '',
    precision     REAL,
    recall        REAL,
    published_at  TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_claims_opp     ON claims(opportunity_id);
CREATE INDEX IF NOT EXISTS idx_claims_cited   ON claims(source_url, source_turn);
CREATE INDEX IF NOT EXISTS idx_decisions_opp  ON decisions(opportunity_id);
CREATE INDEX IF NOT EXISTS idx_outcomes_opp   ON outcomes(opportunity_id);
CREATE INDEX IF NOT EXISTS idx_opps_found     ON opportunities(found_at);
"""


class CitationError(OrchestratorError):
    """A claim arrived without a usable citation. Nothing is stored."""

    status = 400
    code = "citation_required"


class NotFound(OrchestratorError):
    status = 404
    code = "not_found"


def utcnow() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"


def db_path() -> str:
    return os.environ.get("JARVIS_MEMORY_DB", DEFAULT_DB)


def connect() -> sqlite3.Connection:
    path = db_path()
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    conn = sqlite3.connect(path, timeout=20.0)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys = ON")
    conn.execute("PRAGMA journal_mode = WAL")
    conn.execute("PRAGMA synchronous = NORMAL")
    return conn


def init_db() -> str:
    with LOCK:
        conn = connect()
        try:
            conn.executescript(SCHEMA)
            conn.commit()
        finally:
            conn.close()
    return db_path()


# --------------------------------------------------------------------------
# citation enforcement
# --------------------------------------------------------------------------

def _clean(value) -> str:
    return "" if value is None else str(value).strip()


def validate_citation(source_url, source_turn) -> tuple[str, str]:
    """Return the trimmed pair, or raise ``CitationError``.

    Called on EVERY insert path. A claim that cannot point at the exact URL and
    the exact turn it came from does not enter the store.
    """
    url = _clean(source_url)
    turn = _clean(source_turn)
    missing = []
    if not url:
        missing.append("source_url")
    if not turn:
        missing.append("source_turn")
    if missing:
        raise CitationError(
            "a claim must carry a citation: missing " + " and ".join(missing)
            + " — no claim is stored without both a source_url and a source_turn"
        )
    return url, turn


# --------------------------------------------------------------------------
# serialisation helpers
# --------------------------------------------------------------------------

def is_sample(row_id) -> bool:
    return _clean(row_id).startswith(SAMPLE_PREFIX)


def _opportunity(row: sqlite3.Row) -> dict:
    d = dict(row)
    d["sample"] = is_sample(d.get("id"))
    return d


def _claim(row: sqlite3.Row) -> dict:
    d = dict(row)
    d["sample"] = is_sample(d.get("opportunity_id"))
    d["has_citation"] = bool(_clean(d.get("source_url")) and _clean(d.get("source_turn")))
    return d


def _plain(row: sqlite3.Row) -> dict:
    d = dict(row)
    d["sample"] = is_sample(d.get("opportunity_id") or d.get("version"))
    return d


# --------------------------------------------------------------------------
# opportunities
# --------------------------------------------------------------------------

def create_opportunity(*, title, source_url="", found_at=None, status="open", opp_id=None) -> dict:
    title = _clean(title)
    if not title:
        raise ValidationError("opportunity needs a non-empty title")
    opp_id = _clean(opp_id) or "opp-" + datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S%f")
    with LOCK:
        conn = connect()
        try:
            cur = conn.execute(
                "INSERT INTO opportunities (id, title, source_url, found_at, status) VALUES (?,?,?,?,?)",
                (opp_id, title, _clean(source_url), _clean(found_at) or utcnow(), _clean(status) or "open"),
            )
            conn.commit()
        except sqlite3.IntegrityError as exc:
            raise ValidationError(f"could not store opportunity {opp_id!r}: {exc}") from exc
        finally:
            conn.close()
        row = get_opportunity(opp_id)
        audit.record(
            COMPONENT_NAME, "memory.opportunity.created", "memory_opportunity", opp_id,
            {"title": row["title"], "source_url": row["source_url"],
             "found_at": row["found_at"], "status": row["status"]},
        )
        return row


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


def list_opportunities(*, limit: int = 200, status: str | None = None) -> list[dict]:
    sql = "SELECT * FROM opportunities"
    args: list = []
    if status:
        sql += " WHERE status = ?"
        args.append(status)
    sql += " ORDER BY found_at DESC, id DESC LIMIT ?"
    args.append(max(1, int(limit)))
    conn = connect()
    try:
        rows = conn.execute(sql, args).fetchall()
    finally:
        conn.close()
    return [_opportunity(r) for r in rows]


# --------------------------------------------------------------------------
# claims
# --------------------------------------------------------------------------

def create_claim(*, opportunity_id, text, source_url, source_turn, captured_at=None) -> dict:
    """The only write path into ``claims``. Citation is checked FIRST."""
    url, turn = validate_citation(source_url, source_turn)
    body = _clean(text)
    if not body:
        raise ValidationError("claim needs a non-empty text")
    opp_id = _clean(opportunity_id)
    if not opp_id:
        raise ValidationError("claim needs an opportunity_id")
    with LOCK:
        conn = connect()
        try:
            exists = conn.execute(
                "SELECT 1 FROM opportunities WHERE id = ?", (opp_id,)
            ).fetchone()
            if not exists:
                raise NotFound(f"no opportunity with id {opp_id!r}")
            cur = conn.execute(
                "INSERT INTO claims (opportunity_id, text, source_url, source_turn, captured_at)"
                " VALUES (?,?,?,?,?)",
                (opp_id, body, url, turn, _clean(captured_at) or utcnow()),
            )
            conn.commit()
            claim_id = cur.lastrowid
        except sqlite3.IntegrityError as exc:
            raise CitationError(f"claim rejected by the citation constraint: {exc}") from exc
        finally:
            conn.close()
        row = get_claim(claim_id)
        audit.record(
            COMPONENT_NAME, "memory.claim.created", "memory_claim", claim_id,
            {"opportunity_id": row["opportunity_id"], "text": row["text"],
             "source_url": row["source_url"], "source_turn": row["source_turn"]},
        )
        return row


def get_claim(claim_id: int) -> dict | None:
    conn = connect()
    try:
        row = conn.execute(
            "SELECT c.*, o.title AS opportunity_title FROM claims c"
            " LEFT JOIN opportunities o ON o.id = c.opportunity_id WHERE c.id = ?",
            (int(claim_id),),
        ).fetchone()
    finally:
        conn.close()
    return _claim(row) if row else None


def list_claims(*, opportunity_id: str | None = None, limit: int = 200) -> list[dict]:
    sql = (
        "SELECT c.*, o.title AS opportunity_title FROM claims c"
        " LEFT JOIN opportunities o ON o.id = c.opportunity_id"
    )
    args: list = []
    if opportunity_id:
        sql += " WHERE c.opportunity_id = ?"
        args.append(str(opportunity_id))
    sql += " ORDER BY c.id DESC LIMIT ?"
    args.append(max(1, int(limit)))
    conn = connect()
    try:
        rows = conn.execute(sql, args).fetchall()
    finally:
        conn.close()
    return [_claim(r) for r in rows]


# --------------------------------------------------------------------------
# decisions
# --------------------------------------------------------------------------

def create_decision(*, opportunity_id, verdict, rule_version, rationale="", decided_at=None) -> dict:
    verdict = _clean(verdict).lower()
    if verdict not in ("keep", "kill"):
        raise ValidationError("verdict must be 'keep' or 'kill'")
    opp_id = _clean(opportunity_id)
    if not opp_id:
        raise ValidationError("decision needs an opportunity_id")
    version = _clean(rule_version)
    if not version:
        raise ValidationError("decision needs a rule_version")
    with LOCK:
        conn = connect()
        try:
            if not conn.execute("SELECT 1 FROM opportunities WHERE id = ?", (opp_id,)).fetchone():
                raise NotFound(f"no opportunity with id {opp_id!r}")
            if not conn.execute("SELECT 1 FROM rule_versions WHERE version = ?", (version,)).fetchone():
                raise NotFound(f"no rule version {version!r} — publish it first")
            cur = conn.execute(
                "INSERT INTO decisions (opportunity_id, verdict, rule_version, rationale, decided_at)"
                " VALUES (?,?,?,?,?)",
                (opp_id, verdict, version, _clean(rationale), _clean(decided_at) or utcnow()),
            )
            conn.commit()
            decision_id = cur.lastrowid
        finally:
            conn.close()
        row = get_decision(decision_id)
        audit.record(
            COMPONENT_NAME, "memory.decision.created", "memory_decision", decision_id,
            {"opportunity_id": row["opportunity_id"], "verdict": row["verdict"],
             "rule_version": row["rule_version"], "rationale": row["rationale"]},
        )
        return row


def get_decision(decision_id: int) -> dict | None:
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM decisions WHERE id = ?", (int(decision_id),)).fetchone()
    finally:
        conn.close()
    return _plain(row) if row else None


def list_decisions(*, opportunity_id: str | None = None, limit: int = 200) -> list[dict]:
    sql = "SELECT * FROM decisions"
    args: list = []
    if opportunity_id:
        sql += " WHERE opportunity_id = ?"
        args.append(str(opportunity_id))
    sql += " ORDER BY decided_at DESC, id DESC LIMIT ?"
    args.append(max(1, int(limit)))
    conn = connect()
    try:
        rows = conn.execute(sql, args).fetchall()
    finally:
        conn.close()
    return [_plain(r) for r in rows]


def latest_decisions() -> dict[str, dict]:
    """Newest decision per opportunity — what the verdict table shows."""
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT d.* FROM decisions d JOIN ("
            "  SELECT opportunity_id, MAX(id) AS mid FROM decisions GROUP BY opportunity_id"
            ") last ON last.mid = d.id ORDER BY d.decided_at DESC"
        ).fetchall()
    finally:
        conn.close()
    return {r["opportunity_id"]: _plain(r) for r in rows}


# --------------------------------------------------------------------------
# outcomes
# --------------------------------------------------------------------------

def create_outcome(*, opportunity_id, metric, value, measured_at=None) -> dict:
    opp_id = _clean(opportunity_id)
    metric = _clean(metric)
    if not opp_id:
        raise ValidationError("outcome needs an opportunity_id")
    if not metric:
        raise ValidationError("outcome needs a metric name")
    try:
        value = float(value)
    except (TypeError, ValueError):
        raise ValidationError("outcome value must be a number") from None
    with LOCK:
        conn = connect()
        try:
            if not conn.execute("SELECT 1 FROM opportunities WHERE id = ?", (opp_id,)).fetchone():
                raise NotFound(f"no opportunity with id {opp_id!r}")
            cur = conn.execute(
                "INSERT INTO outcomes (opportunity_id, metric, value, measured_at) VALUES (?,?,?,?)",
                (opp_id, metric, value, _clean(measured_at) or utcnow()),
            )
            conn.commit()
            outcome_id = cur.lastrowid
        finally:
            conn.close()
        row = get_outcome(outcome_id)
        audit.record(
            COMPONENT_NAME, "memory.outcome.created", "memory_outcome", outcome_id,
            {"opportunity_id": row["opportunity_id"], "metric": row["metric"],
             "value": row["value"], "measured_at": row["measured_at"]},
        )
        return row


def get_outcome(outcome_id: int) -> dict | None:
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM outcomes WHERE id = ?", (int(outcome_id),)).fetchone()
    finally:
        conn.close()
    return _plain(row) if row else None


def list_outcomes(*, opportunity_id: str | None = None, limit: int = 200) -> list[dict]:
    sql = "SELECT * FROM outcomes"
    args: list = []
    if opportunity_id:
        sql += " WHERE opportunity_id = ?"
        args.append(str(opportunity_id))
    sql += " ORDER BY measured_at DESC, id DESC LIMIT ?"
    args.append(max(1, int(limit)))
    conn = connect()
    try:
        rows = conn.execute(sql, args).fetchall()
    finally:
        conn.close()
    return [_plain(r) for r in rows]


# --------------------------------------------------------------------------
# rule versions
# --------------------------------------------------------------------------

def create_rule(*, version, description="", precision=None, recall=None, published_at=None) -> dict:
    version = _clean(version)
    if not version:
        raise ValidationError("rule version needs a version string")
    try:
        prec = None if precision in (None, "") else float(precision)
        rec = None if recall in (None, "") else float(recall)
    except (TypeError, ValueError):
        raise ValidationError("precision and recall must be numbers between 0 and 1") from None
    for label, val in (("precision", prec), ("recall", rec)):
        if val is not None and not (0.0 <= val <= 1.0):
            raise ValidationError(f"{label} must be between 0 and 1")
    with LOCK:
        conn = connect()
        try:
            conn.execute(
                "INSERT OR REPLACE INTO rule_versions (version, description, precision, recall, published_at)"
                " VALUES (?,?,?,?,?)",
                (version, _clean(description), prec, rec, _clean(published_at) or utcnow()),
            )
            conn.commit()
        finally:
            conn.close()
    row = next((r for r in list_rules() if r["version"] == version), {})
    audit.record(
        COMPONENT_NAME, "memory.rule.published", "memory_rule_version", version,
        {"description": row.get("description", ""), "precision": row.get("precision"),
         "recall": row.get("recall"), "published_at": row.get("published_at")},
    )
    return row


def list_rules(limit: int = 200) -> list[dict]:
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM rule_versions ORDER BY published_at DESC, version DESC LIMIT ?",
            (max(1, int(limit)),),
        ).fetchall()
    finally:
        conn.close()
    return [dict(r) for r in rows]


def get_rule(version: str) -> dict | None:
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM rule_versions WHERE version = ?", (str(version),)).fetchone()
    finally:
        conn.close()
    return dict(row) if row else None


# --------------------------------------------------------------------------
# search + stats
# --------------------------------------------------------------------------

def _escape_like(term: str) -> str:
    return term.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")


def search(q: str, limit: int = 100) -> dict:
    """LIKE search over claims.text and opportunities.title."""
    term = _clean(q)
    limit = max(1, min(int(limit or 100), 500))
    if not term:
        return {"query": "", "claims": [], "opportunities": [], "claim_count": 0,
                "opportunity_count": 0, "citations_visible": 0}
    like = "%" + _escape_like(term) + "%"
    conn = connect()
    try:
        claim_rows = conn.execute(
            "SELECT c.*, o.title AS opportunity_title FROM claims c"
            " LEFT JOIN opportunities o ON o.id = c.opportunity_id"
            " WHERE c.text LIKE ? ESCAPE '\\' OR o.title LIKE ? ESCAPE '\\'"
            " ORDER BY c.id DESC LIMIT ?",
            (like, like, limit),
        ).fetchall()
        opp_rows = conn.execute(
            "SELECT * FROM opportunities WHERE title LIKE ? ESCAPE '\\'"
            " ORDER BY found_at DESC, id DESC LIMIT ?",
            (like, limit),
        ).fetchall()
    finally:
        conn.close()
    claims = [_claim(r) for r in claim_rows]
    return {
        "query": term,
        "claims": claims,
        "opportunities": [_opportunity(r) for r in opp_rows],
        "claim_count": len(claims),
        "opportunity_count": len(opp_rows),
        "citations_visible": sum(1 for c in claims if c["has_citation"]),
    }


def stats() -> dict:
    conn = connect()
    try:
        total_opps = conn.execute("SELECT COUNT(*) FROM opportunities").fetchone()[0]
        total_claims = conn.execute("SELECT COUNT(*) FROM claims").fetchone()[0]
        cited = conn.execute(
            "SELECT COUNT(*) FROM claims WHERE length(trim(source_url)) > 0"
            " AND length(trim(source_turn)) > 0"
        ).fetchone()[0]
        decisions = conn.execute("SELECT COUNT(*) FROM decisions").fetchone()[0]
        outcomes = conn.execute("SELECT COUNT(*) FROM outcomes").fetchone()[0]
        rules = conn.execute("SELECT COUNT(*) FROM rule_versions").fetchone()[0]
        keeps = conn.execute("SELECT COUNT(*) FROM decisions WHERE verdict = 'keep'").fetchone()[0]
        kills = conn.execute("SELECT COUNT(*) FROM decisions WHERE verdict = 'kill'").fetchone()[0]
        samples = conn.execute(
            "SELECT COUNT(*) FROM opportunities WHERE id LIKE ?", (SAMPLE_PREFIX + "%",)
        ).fetchone()[0]
    finally:
        conn.close()
    pct = round((cited / total_claims) * 100, 1) if total_claims else 100.0
    return {
        "total_opportunities": total_opps,
        "total_claims": total_claims,
        "claims_with_citations": cited,
        "pct_claims_with_citations": pct,
        "total_decisions": decisions,
        "total_outcomes": outcomes,
        "rule_versions": rules,
        "keeps": keeps,
        "kills": kills,
        "sample_opportunities": samples,
        "db_path": db_path(),
    }


# --------------------------------------------------------------------------
# seed — first run only, clearly labelled sample data
# --------------------------------------------------------------------------

SEED_OPPORTUNITIES = [
    {
        "id": "sample-opp-1",
        "title": "Bookkeeping automation for solo dental practices",
        "source_url": "https://news.ycombinator.com/item?id=41200001",
        "found_at": "2026-11-02T09:14:00Z",
        "status": "kept",
    },
    {
        "id": "sample-opp-2",
        "title": "Compliance-ready shift scheduling for small restaurant groups",
        "source_url": "https://www.reddit.com/r/restaurateur/comments/sample_shifts",
        "found_at": "2026-11-06T16:42:00Z",
        "status": "killed",
    },
    {
        "id": "sample-opp-3",
        "title": "Vendor security questionnaire autofill for 20-person SaaS teams",
        "source_url": "https://news.ycombinator.com/item?id=41200999",
        "found_at": "2026-11-12T11:03:00Z",
        "status": "open",
    },
]

SEED_CLAIMS = [
    ("sample-opp-1", "Practice owner says month-end reconciliation eats two full days per month.",
     "https://news.ycombinator.com/item?id=41200001", "sample-t1", "2026-11-02T09:14:00Z"),
    ("sample-opp-1", "Three separate commenters name the same dental practice-management tool as the bottleneck.",
     "https://news.ycombinator.com/item?id=41200001#41200312", "sample-t1", "2026-11-02T09:15:00Z"),
    ("sample-opp-2", "Restaurant group operator says scheduling across four locations is done in a shared spreadsheet.",
     "https://www.reddit.com/r/restaurateur/comments/sample_shifts", "sample-t2", "2026-11-06T16:42:00Z"),
    ("sample-opp-2", "Two respondents say they would not pay more than $50/month for scheduling alone.",
     "https://www.reddit.com/r/restaurateur/comments/sample_shifts#reply-2", "sample-t2", "2026-11-06T16:44:00Z"),
    ("sample-opp-3", "Security lead at a 24-person SaaS says each vendor questionnaire takes ~3 hours.",
     "https://news.ycombinator.com/item?id=41200999", "sample-t3", "2026-11-12T11:03:00Z"),
    ("sample-opp-3", "Buyer explicitly asks for a tool that cites the policy paragraph it used to answer.",
     "https://news.ycombinator.com/item?id=41200999#41201150", "sample-t3", "2026-11-12T11:05:00Z"),
]

SEED_DECISIONS = [
    ("sample-opp-1", "keep", "v0.3.0",
     "Two independent citations, recurring pain, named buyer (practice owner).",
     "2026-11-03T08:00:00Z"),
    ("sample-opp-2", "kill", "v0.2.0",
     "Willingness to pay sits below the $80/month floor in rule v0.2.0.",
     "2026-11-07T08:30:00Z"),
    ("sample-opp-3", "keep", "v0.3.0",
     "Buyer asks for citations explicitly; all cited URLs resolved on re-check.",
     "2026-11-13T07:45:00Z"),
]

SEED_OUTCOMES = [
    ("sample-opp-1", "paid_pilots", 3.0, "2026-11-15T12:00:00Z"),
    ("sample-opp-3", "discovery_calls", 5.0, "2026-11-16T12:00:00Z"),
]


def seed_if_empty() -> dict:
    """Insert the sample bundle once. Never duplicates, never overwrites."""
    with LOCK:
        conn = connect()
        try:
            existing = conn.execute("SELECT COUNT(*) FROM opportunities").fetchone()[0]
            rules_existing = conn.execute("SELECT COUNT(*) FROM rule_versions").fetchone()[0]
            seeded = False
            if rules_existing == 0:
                conn.executemany(
                    "INSERT INTO rule_versions (version, description, precision, recall, published_at)"
                    " VALUES (?,?,?,?,?)",
                    [(r["version"], r["description"], r["precision"], r["recall"], r["published_at"])
                     for r in SEED_RULES],
                )
                seeded = True
            if existing == 0:
                conn.executemany(
                    "INSERT INTO opportunities (id, title, source_url, found_at, status)"
                    " VALUES (?,?,?,?,?)",
                    [(o["id"], o["title"], o["source_url"], o["found_at"], o["status"])
                     for o in SEED_OPPORTUNITIES],
                )
                # Seed claims go through the SAME citation gate as the API.
                for opp_id, text, url, turn, captured in SEED_CLAIMS:
                    url, turn = validate_citation(url, turn)
                    conn.execute(
                        "INSERT INTO claims (opportunity_id, text, source_url, source_turn, captured_at)"
                        " VALUES (?,?,?,?,?)",
                        (opp_id, text, url, turn, captured),
                    )
                conn.executemany(
                    "INSERT INTO decisions (opportunity_id, verdict, rule_version, rationale, decided_at)"
                    " VALUES (?,?,?,?,?)",
                    SEED_DECISIONS,
                )
                conn.executemany(
                    "INSERT INTO outcomes (opportunity_id, metric, value, measured_at)"
                    " VALUES (?,?,?,?)",
                    SEED_OUTCOMES,
                )
                seeded = True
            conn.commit()
        finally:
            conn.close()
    return {"seeded": seeded, "db_path": db_path()}
