"""THE OUTREACH ENGINE — email-first, draft-only, structurally unable to send.

The hard rule
-------------
There is no send path in this module, and there is no way to add one by
accident: the module imports no mail library, opens no SMTP socket, makes no
HTTP call, and exposes no function whose name or behaviour transmits anything.
The only verbs are ``create_draft`` and ``approve_draft``. Approval moves a
draft from ``draft`` to ``approved`` — a label that means "a human has read this
and may now copy it into their own mail client". Nothing leaves the process.

``tests/test_outreach.py`` asserts this structurally: it walks every route in
the Flask app and fails if any of them is a send path, and it greps this module
for smtplib / socket / requests / urllib.

The lead store
--------------
``leads`` and ``outreach_drafts`` live in the existing memory SQLite file
(``data/jarvis.db``, the same file as opportunities/claims/decisions), so a lead
survives a restart. Every lead carries a ``source_url`` that is NOT NULL and
CHECKed non-blank — a lead you cannot cite is a lead you do not get to keep,
the same rule the memory store enforces on claims.

Seeded leads
------------
Five NY leads derived from the 2026-11-18 captures in ``live_data``. One is a
real business named in the Marketcheck capture; the other four are segment
leads — the signal identifies the segment, not a named company, and the row says
so (``lead_kind = 'segment'``) rather than inventing a business name. Enumerating
the actual businesses in those segments is what the Mapbox adapter is for, and
Mapbox is NEEDS KEY, so the page says the names are pending.
"""

from __future__ import annotations

import json
import logging
import sqlite3
import threading
from datetime import datetime, timezone

from . import audit
from . import db as opdb
from . import memory
from .errors import NotFound, ValidationError

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

COMPONENT_NAME = "OutreachEngine"

LOCK = threading.RLock()

LEAD_STATUSES = ("new", "drafted", "approved")

#: Shown on the page and returned by the API. This is a rule, not a suggestion.
COMPLIANCE = (
    "Business addresses only. No personal addresses, no consumer/home addresses, "
    "no scraped individual contact details. Every draft is addressed to a business "
    "and cites the public source the problem came from. Nothing is sent by this "
    "system: there is no SMTP client, no mail API and no send route."
)
DRAFT_STATUSES = ("draft", "approved")

SCHEMA = """
CREATE TABLE IF NOT EXISTS leads (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    business      TEXT NOT NULL,
    category      TEXT NOT NULL,
    city          TEXT NOT NULL,
    region        TEXT NOT NULL,
    problem       TEXT NOT NULL,
    proposed_bot  TEXT NOT NULL,
    source_url    TEXT NOT NULL CHECK (length(trim(source_url)) > 0),
    source_note   TEXT NOT NULL DEFAULT '',
    lead_kind     TEXT NOT NULL DEFAULT 'segment',
    status        TEXT NOT NULL DEFAULT 'new',
    is_seed       INTEGER NOT NULL DEFAULT 0,
    created_at    TEXT NOT NULL,
    updated_at    TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS outreach_drafts (
    id            INTEGER PRIMARY KEY AUTOINCREMENT,
    lead_id       INTEGER NOT NULL REFERENCES leads(id),
    subject       TEXT NOT NULL,
    body          TEXT NOT NULL,
    problem       TEXT NOT NULL,
    bot_id        INTEGER,
    status        TEXT NOT NULL DEFAULT 'draft',
    created_at    TEXT NOT NULL,
    approved_at   TEXT,
    approved_by   TEXT
);

CREATE INDEX IF NOT EXISTS idx_leads_status ON leads(status);
CREATE INDEX IF NOT EXISTS idx_drafts_lead  ON outreach_drafts(lead_id);
"""


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


def connect() -> sqlite3.Connection:
    return memory.connect()


def init_db() -> str:
    with LOCK:
        conn = connect()
        try:
            conn.executescript(SCHEMA)
            # Migration: older databases predate the KEPT-bot linkage.
            cols = {r[1] for r in conn.execute("PRAGMA table_info(outreach_drafts)")}
            if "bot_id" not in cols:
                conn.execute("ALTER TABLE outreach_drafts ADD COLUMN bot_id INTEGER")
            conn.commit()
        finally:
            conn.close()
    return memory.db_path()


# ---------------------------------------------------------------------------
# Seeded leads — derived from the 2026-11-18 captures, each with its citation
# ---------------------------------------------------------------------------
MARKETCHECK_URL = "https://www.marketcheck.com/automotive/search?zip=14620&radius=25&car_type=used"
XWEATHER_URL = "https://www.xweather.com/weather/forecast/rochester-ny"
FINDATASETS_URL = "https://financialdatasets.ai/news"

SEED_LEADS = [
    {
        "business": "Greenlight Auto Sales",
        "category": "Used-car dealer",
        "city": "Rochester",
        "region": "NY",
        "problem": ("A 2016 Chevrolet Silverado 1500 Double Cab has sat at $17,924 for 152 days on market — "
                    "roughly five times the 14- and 22-day turns on the same lot. Floorplan cost is accruing "
                    "and the listing is not moving on price alone."),
        "proposed_bot": "Stale-inventory re-pricing bot: watches days-on-market per VIN, drafts a price/photo/"
                        "description change when a unit crosses 90 days, and reports the delta weekly.",
        "source_url": MARKETCHECK_URL,
        "source_note": ("Marketcheck capture 2026-11-18: 3,955 used listings within 25 mi of Rochester 14620. "
                        "VIN 1GCVKRECXGZ353116, 152 days on market. Dealer domain from the same capture: "
                        "greenlightautosalesny.mycarsonline.com"),
        "lead_kind": "captured",
    },
    {
        "business": "Rochester HVAC contractor (segment lead)",
        "category": "HVAC contractor",
        "city": "Rochester",
        "region": "NY",
        "problem": ("Nov 19 is forecast at 62°F/46°F and Nov 20 at 60°F/39°F with 0% precipitation — a mild, dry "
                    "stretch that suppresses heating calls and emergency no-heat work for at least three days. "
                    "The demand dip is knowable two days ahead and nobody is filling the calendar with it."),
        "proposed_bot": "Demand-dip fill bot: reads the 3-day forecast, and when a mild stretch is coming, drafts "
                        "maintenance-tuneup outreach to the contractor's own past-customer list to fill the gap.",
        "source_url": XWEATHER_URL,
        "source_note": "Xweather capture 2026-11-18: Rochester NY 3-day forecast, 0% precip on all three days.",
        "lead_kind": "segment",
    },
    {
        "business": "Rochester homebuilder (segment lead)",
        "category": "Homebuilder",
        "city": "Rochester",
        "region": "NY",
        "problem": ("Homebuilder confidence has sunk to a 14-year low as buyers hibernate. Builders respond by "
                    "cutting marketing spend, which is exactly backwards: the pipeline needs more qualified "
                    "buyers, not fewer, and the inventory is already standing."),
        "proposed_bot": "Buyer-reactivation bot: works the builder's dormant inquiry list with a specific "
                        "incentive, and reports cost-per-appointment against the marketing spend it replaces.",
        "source_url": FINDATASETS_URL,
        "source_note": ("Financial Datasets capture 2026-11-18: \"Homebuilder confidence sinks to a 14-year low "
                        "as buyers hibernate\" — HousingWire, 2026-11-17."),
        "lead_kind": "segment",
    },
    {
        "business": "Rochester roofing contractor (segment lead)",
        "category": "Roofing contractor",
        "city": "Rochester",
        "region": "NY",
        "problem": ("Three consecutive dry, sunny days at 57–62°F with 0% precipitation means no storm-driven "
                    "repair demand this week. Roofers who only work storm leads go quiet; the install and "
                    "maintenance backlog is the only work available and it is not being worked."),
        "proposed_bot": "Dry-spell backlog bot: when no precipitation is forecast for 72h, drafts maintenance and "
                        "replacement outreach to past customers and quotes the install window the weather allows.",
        "source_url": XWEATHER_URL,
        "source_note": "Xweather capture 2026-11-18: Nov 18–20 all 0% precipitation, mostly sunny to sunny.",
        "lead_kind": "segment",
    },
    {
        "business": "Rochester landscaper (segment lead)",
        "category": "Landscaping contractor",
        "city": "Rochester",
        "region": "NY",
        "problem": ("A 62°F Thursday and 60°F Friday in mid-November extend the leaf-cleanup and final-mow window "
                    "by roughly a week. That window closes hard at the first hard freeze, and the crews that "
                    "could be booked into it are not being booked."),
        "proposed_bot": "Season-window bot: watches the forecast for the last workable week of the season and "
                        "drafts a one-week booking push to the existing customer list before the freeze.",
        "source_url": XWEATHER_URL,
        "source_note": "Xweather capture 2026-11-18: Nov 19 62°F/46°F, Nov 20 60°F/39°F, 0% precip.",
        "lead_kind": "segment",
    },
]


# ---------------------------------------------------------------------------
# Reads
# ---------------------------------------------------------------------------
def _lead_row(row) -> dict:
    return {
        "id": row["id"],
        "business": row["business"],
        "category": row["category"],
        "city": row["city"],
        "region": row["region"],
        "problem": row["problem"],
        "proposed_bot": row["proposed_bot"],
        "source_url": row["source_url"],
        "source_note": row["source_note"],
        "lead_kind": row["lead_kind"],
        "status": row["status"],
        "is_seed": bool(row["is_seed"]),
        "created_at": row["created_at"],
        "updated_at": row["updated_at"],
    }


def _draft_row(row) -> dict:
    return {
        "id": row["id"],
        "lead_id": row["lead_id"],
        "subject": row["subject"],
        "body": row["body"],
        "problem": row["problem"],
        "bot_id": row["bot_id"] if "bot_id" in row.keys() else None,
        "status": row["status"],
        "created_at": row["created_at"],
        "approved_at": row["approved_at"],
        "approved_by": row["approved_by"],
    }


def list_leads() -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute("SELECT * FROM leads ORDER BY id").fetchall()
        leads = [_lead_row(r) for r in rows]
        drafts = {d["lead_id"]: d for d in
                  [_draft_row(r) for r in conn.execute(
                      "SELECT * FROM outreach_drafts ORDER BY id DESC").fetchall()]}
        for lead in leads:
            lead["draft"] = drafts.get(lead["id"])
        return leads
    finally:
        conn.close()


def get_lead(lead_id: int) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM leads WHERE id = ?", (lead_id,)).fetchone()
        if row is None:
            return None
        lead = _lead_row(row)
        draft = conn.execute(
            "SELECT * FROM outreach_drafts WHERE lead_id = ? ORDER BY id DESC LIMIT 1", (lead_id,)
        ).fetchone()
        lead["draft"] = _draft_row(draft) if draft else None
        return lead
    finally:
        conn.close()


def list_drafts() -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT d.*, l.business, l.category, l.city, l.region, l.source_url "
            "FROM outreach_drafts d JOIN leads l ON l.id = d.lead_id ORDER BY d.id DESC"
        ).fetchall()
        out = []
        for row in rows:
            draft = _draft_row(row)
            draft.update({
                "business": row["business"],
                "category": row["category"],
                "city": row["city"],
                "region": row["region"],
                "source_url": row["source_url"],
            })
            out.append(draft)
        return out
    finally:
        conn.close()


def counts() -> dict:
    init_db()
    conn = connect()
    try:
        leads = conn.execute("SELECT COUNT(*) AS n FROM leads").fetchone()["n"]
        drafts = conn.execute("SELECT COUNT(*) AS n FROM outreach_drafts").fetchone()["n"]
        approved = conn.execute(
            "SELECT COUNT(*) AS n FROM outreach_drafts WHERE status = 'approved'").fetchone()["n"]
        return {"leads": leads, "drafts": drafts, "approved": approved,
                "awaiting_approval": drafts - approved}
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# Writes
# ---------------------------------------------------------------------------
def create_lead(*, business: str, category: str, city: str, region: str, problem: str,
                proposed_bot: str, source_url: str, source_note: str = "",
                lead_kind: str = "segment", is_seed: bool = False) -> dict:
    """Insert one lead. A blank citation is refused before any SQL runs."""
    for field, value in (("business", business), ("category", category), ("city", city),
                         ("region", region), ("problem", problem), ("proposed_bot", proposed_bot)):
        if not str(value or "").strip():
            raise ValidationError(f"lead field {field!r} is required")
    if not str(source_url or "").strip():
        raise ValidationError("a lead needs a source_url — no citation, no lead")
    now = utcnow()
    with LOCK:
        init_db()
        conn = connect()
        try:
            cur = conn.execute(
                "INSERT INTO leads (business, category, city, region, problem, proposed_bot, "
                "source_url, source_note, lead_kind, status, is_seed, created_at, updated_at) "
                "VALUES (?,?,?,?,?,?,?,?,?,'new',?,?,?)",
                (business.strip(), category.strip(), city.strip(), region.strip(), problem.strip(),
                 proposed_bot.strip(), source_url.strip(), source_note.strip(), lead_kind,
                 1 if is_seed else 0, now, now),
            )
            lead_id = cur.lastrowid
            conn.commit()
        finally:
            conn.close()
    audit.record(
        actor=COMPONENT_NAME,
        action="outreach.lead.created",
        subject_type="lead",
        subject_id=str(lead_id),
        payload={"business": business, "category": category, "city": city, "region": region,
                 "source_url": source_url, "lead_kind": lead_kind, "is_seed": is_seed},
    )
    return get_lead(lead_id)


def seed_if_empty() -> int:
    """Insert the five seeded leads once. Idempotent."""
    init_db()
    conn = connect()
    try:
        existing = conn.execute("SELECT COUNT(*) AS n FROM leads").fetchone()["n"]
    finally:
        conn.close()
    if existing:
        return 0
    created = 0
    for lead in SEED_LEADS:
        create_lead(**lead, is_seed=True)
        created += 1
    if created:
        audit.record(
            actor=COMPONENT_NAME,
            action="outreach.leads.seeded",
            subject_type="lead_store",
            subject_id="seed",
            payload={"count": created, "capture_date": "2026-11-18",
                     "sources": sorted({lead["source_url"] for lead in SEED_LEADS})},
        )
    return created


# ---------------------------------------------------------------------------
# Draft generation — plain text, no send
# ---------------------------------------------------------------------------
def _first_name(business: str) -> str:
    return business.split("(")[0].strip()


# ---------------------------------------------------------------------------
# KEPT bots — the only bots an outreach draft may be generated from
# ---------------------------------------------------------------------------
def kept_bots() -> list[dict]:
    """Every bot whose measurement verdict is KEPT. Read-only, straight from the DB.

    A bot that was KILLED, is still a SPEC, or was retired is not offered: the
    outreach engine only speaks for bots that earned a keep.
    """
    # bot_specs / bot_decisions live in the OPERATIONAL db (orchestrator.db),
    # not the memory db that holds leads and drafts.
    conn = opdb.connect()
    try:
        rows = conn.execute(
            "SELECT s.id, s.opportunity_id, s.spec_json, s.created_at, s.status, "
            "       d.verdict, d.reason, d.decided_at, d.rule_version "
            "FROM bot_specs s JOIN bot_decisions d ON d.bot_id = s.id "
            "WHERE d.verdict = 'KEPT' AND COALESCE(s.retired, 0) = 0 "
            "ORDER BY s.id ASC"
        ).fetchall()
    except sqlite3.OperationalError:
        rows = []          # a fresh db with no bot tables yet: no kept bots
    finally:
        conn.close()
    out = []
    for row in rows:
        try:
            spec = json.loads(row["spec_json"] or "{}")
        except (TypeError, ValueError):
            spec = {}
        opp = spec.get("opportunity") or {}
        out.append({
            "id": row["id"],
            "bot_name": spec.get("bot_name") or f"bot-{row['id']}",
            "purpose": spec.get("purpose") or "",
            "opportunity_id": row["opportunity_id"],
            "opportunity_title": opp.get("title") or "",
            "business_type": opp.get("business_type") or "",
            "verdict": row["verdict"],
            "verdict_reason": row["reason"] or "",
            "decided_at": row["decided_at"],
            "rule_version": row["rule_version"],
            "estimated_monthly_value_usd": spec.get("estimated_monthly_value_usd"),
            "estimated_monthly_cost_usd": spec.get("estimated_monthly_cost_usd"),
            "roi_ratio": spec.get("roi_ratio"),
            "requires_human_approval": bool(spec.get("requires_human_approval")),
            "deployed": bool((spec.get("deployment") or {}).get("deployed")),
            "honesty": spec.get("honesty") or "",
        })
    return out


def get_kept_bot(bot_id: int) -> dict | None:
    for bot in kept_bots():
        if int(bot["id"]) == int(bot_id):
            return bot
    return None


def compose_draft_for_bot(bot: dict, lead: dict) -> dict:
    """Build the plain-text draft for a KEPT bot + a business lead. Pure, no I/O."""
    business = _first_name(lead["business"])
    city, region = lead["city"], lead["region"]
    subject = f"{business} — {bot['bot_name']} (kept bot, {city} {region})"
    body = "\n".join([
        f"Subject: {subject}",
        "",
        f"Hi {business} team,",
        "",
        f"I run a small automation shop in {city}, {region}. I build one bot at a time, measure it, "
        f"and keep only the ones that pay for themselves. This one was kept:",
        "",
        f"  Bot: {bot['bot_name']}",
        f"  What it does: {bot['purpose']}",
        "",
        "The specific problem it addresses for you:",
        "",
        f"  {lead['problem']}",
        "",
        f"Why it was kept: {bot['verdict_reason']}",
        "",
        "It runs on your existing list and your existing tools. No new software for your team to "
        "learn, no long contract — a four-week pilot, and you keep the data either way.",
        "",
        "Worth 15 minutes this week? If not, tell me what would make it worth 15 minutes and I'll "
        "come back with that instead.",
        "",
        "—",
        f"Source for the problem above: {lead['source_url']}",
        f"({lead['source_note']})",
        "",
        "DRAFT — not sent. Review, edit, and send it yourself.",
    ])
    return {"subject": subject, "body": body, "problem": lead["problem"]}


def create_draft_from_bot(bot_id: int, lead_id: int) -> dict:
    """Generate and store a draft from a KEPT bot for one business lead.

    Stores status='draft'. Nothing is transmitted: this function has no send path
    and the module imports no mail library.
    """
    bot = get_kept_bot(bot_id)
    if bot is None:
        raise NotFound(f"no KEPT bot with id {bot_id}")
    lead = get_lead(lead_id)
    if lead is None:
        raise NotFound(f"no lead with id {lead_id}")
    composed = compose_draft_for_bot(bot, lead)
    now = utcnow()
    with LOCK:
        conn = connect()
        try:
            conn.execute(
                "DELETE FROM outreach_drafts WHERE lead_id = ? AND bot_id = ?", (lead_id, bot_id)
            )
            cur = conn.execute(
                "INSERT INTO outreach_drafts (lead_id, subject, body, problem, bot_id, status, created_at) "
                "VALUES (?,?,?,?,?,'draft',?)",
                (lead_id, composed["subject"], composed["body"], composed["problem"], bot_id, now),
            )
            draft_id = cur.lastrowid
            conn.execute("UPDATE leads SET status = 'drafted', updated_at = ? WHERE id = ?",
                         (now, lead_id))
            conn.commit()
        finally:
            conn.close()
    audit.record(
        actor=COMPONENT_NAME,
        action="outreach.draft.created",
        subject_type="draft",
        subject_id=str(draft_id),
        payload={"lead_id": lead_id, "bot_id": bot_id, "bot_name": bot["bot_name"],
                 "business": lead["business"], "subject": composed["subject"],
                 "status": "draft", "sent": False,
                 "note": "draft only — nothing transmitted"},
    )
    return get_draft(draft_id)


def compose_draft(lead: dict) -> dict:
    """Build the plain-text draft for one lead. Pure function, no I/O."""
    business = _first_name(lead["business"])
    city, region = lead["city"], lead["region"]
    subject = f"{city} {lead['category'].lower()} — {lead['proposed_bot'].split(':')[0].lower()}"
    body = "\n".join([
        f"Subject: {subject}",
        "",
        f"Hi {business} team,",
        "",
        f"I run a small automation shop in {city}, {region}. I look at local market data every morning and "
        f"one thing stood out for you this week:",
        "",
        f"  {lead['problem']}",
        "",
        f"What I'd build for you: {lead['proposed_bot']}",
        "",
        "It runs on your existing list and your existing tools. No new software for your team to learn, "
        "no long contract — a four-week pilot, and you keep the data either way.",
        "",
        "Worth 15 minutes this week? If not, tell me what would make it worth 15 minutes and I'll come back "
        "with that instead.",
        "",
        "—",
        f"Source for the above: {lead['source_url']}",
        f"({lead['source_note']})",
        "",
        "DRAFT — not sent. Review, edit, and send it yourself.",
    ])
    return {"subject": subject, "body": body, "problem": lead["problem"]}


def create_draft(lead_id: int) -> dict:
    """Generate and store a draft for one lead. Replaces any earlier draft."""
    lead = get_lead(lead_id)
    if lead is None:
        raise NotFound(f"no lead with id {lead_id}")
    composed = compose_draft(lead)
    now = utcnow()
    with LOCK:
        conn = connect()
        try:
            conn.execute("DELETE FROM outreach_drafts WHERE lead_id = ?", (lead_id,))
            cur = conn.execute(
                "INSERT INTO outreach_drafts (lead_id, subject, body, problem, status, created_at) "
                "VALUES (?,?,?,?,'draft',?)",
                (lead_id, composed["subject"], composed["body"], composed["problem"], now),
            )
            draft_id = cur.lastrowid
            conn.execute("UPDATE leads SET status = 'drafted', updated_at = ? WHERE id = ?",
                         (now, lead_id))
            conn.commit()
        finally:
            conn.close()
    audit.record(
        actor=COMPONENT_NAME,
        action="outreach.draft.created",
        subject_type="draft",
        subject_id=str(draft_id),
        payload={"lead_id": lead_id, "business": lead["business"], "subject": composed["subject"],
                 "status": "draft", "sent": False,
                 "note": "draft only — nothing transmitted"},
    )
    return get_draft(draft_id)


def get_draft(draft_id: int) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute(
            "SELECT d.*, l.business, l.category, l.city, l.region, l.source_url "
            "FROM outreach_drafts d JOIN leads l ON l.id = d.lead_id WHERE d.id = ?", (draft_id,)
        ).fetchone()
        if row is None:
            return None
        draft = _draft_row(row)
        draft.update({"business": row["business"], "category": row["category"],
                      "city": row["city"], "region": row["region"], "source_url": row["source_url"]})
        return draft
    finally:
        conn.close()


def approve_draft(draft_id: int, approved_by: str = "operator") -> dict:
    """The approval gate. Marks a draft ready to send — and sends nothing."""
    draft = get_draft(draft_id)
    if draft is None:
        raise NotFound(f"no draft with id {draft_id}")
    if draft["status"] == "approved":
        return draft
    now = utcnow()
    with LOCK:
        conn = connect()
        try:
            conn.execute(
                "UPDATE outreach_drafts SET status = 'approved', approved_at = ?, approved_by = ? "
                "WHERE id = ?", (now, approved_by, draft_id),
            )
            conn.execute("UPDATE leads SET status = 'approved', updated_at = ? WHERE id = ?",
                         (now, draft["lead_id"]))
            conn.commit()
        finally:
            conn.close()
    audit.record(
        actor=COMPONENT_NAME,
        action="outreach.draft.approved",
        subject_type="draft",
        subject_id=str(draft_id),
        payload={"lead_id": draft["lead_id"], "business": draft["business"],
                 "approved_by": approved_by, "approved_at": now,
                 "status": "approved", "sent": False,
                 "note": "approved for manual sending — nothing transmitted by this system"},
    )
    return get_draft(draft_id)


def snapshot() -> dict:
    return {
        "leads": list_leads(),
        "drafts": list_drafts(),
        "counts": counts(),
        "kept_bots": kept_bots(),
        "banner": "Drafts only. Nothing is sent. You copy and send manually.",
        "compliance": COMPLIANCE,
        "send_path": None,
        "send_routes": [],
        "smtp_configured": False,
        "sent_count": 0,
        "approval_required": True,
    }
