"""Tests for the three surfaces completed in this pass:

  1. LIVE DATA signals — STALE INVENTORY (>120 DOM), DEMAND DIP (0% precip),
     TREND headlines, and the literal Massive NOT ENTITLED reason.
  2. The IN-PROCESS SCHEDULER LOOP — real thread, persisted state, manual run.
  3. OUTREACH — KEPT-bot drafts, status 'draft', approval gate, and the
     structural guarantee that no send route / SMTP code exists.
"""

from __future__ import annotations

import os
import re
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-finish-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")
os.environ["JARVIS_MEMORY_DB"] = os.path.join(_TMP, "data", "jarvis.db")

from orchestrator import audit  # noqa: E402
from orchestrator import live_data  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import outreach  # noqa: E402
from orchestrator import scheduler_loop  # noqa: E402
from orchestrator import scheduling  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import init_db  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    audit.init_db()
    memory.init_db()
    scheduling.init_db()
    outreach.init_db()
    live_data.reset_for_tests()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


@pytest.fixture
def client():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    return app.test_client()


# --------------------------------------------------------------------------
# 1. LIVE DATA signals
# --------------------------------------------------------------------------
def test_marketcheck_stale_inventory_signal_over_120_days():
    rows = [
        ["2015 JEEP WRANGLER", "$16,424", "119,000 mi", "1C4HJWEG5FL740904", "14", "d"],
        ["2016 CHEVROLET SILVERADO", "$17,924", "91,500 mi", "1GCVKRECXGZ353116", "152", "—"],
    ]
    cols = ["Vehicle", "Price", "Mileage", "VIN", "Days on market", "Dealer"]
    sigs = live_data._signals("marketcheck", rows, cols)
    assert len(sigs) == 1
    assert sigs[0]["kind"] == "STALE INVENTORY"
    assert sigs[0]["value"] == 152
    assert sigs[0]["vin"] == "1GCVKRECXGZ353116"
    assert "120-day threshold" in sigs[0]["line"]


def test_marketcheck_no_signal_at_or_below_threshold():
    rows = [["A", "$1", "1 mi", "VIN1", "120", "d"]]
    cols = ["Vehicle", "Price", "Mileage", "VIN", "Days on market", "Dealer"]
    assert live_data._signals("marketcheck", rows, cols) == []


def test_xweather_zero_precip_demand_dip():
    rows = [["Nov 18", "Sunny", "57°F / 38°F", "0%"],
            ["Nov 19", "Sunny", "62°F / 46°F", "0%"],
            ["Nov 20", "Sunny", "60°F / 39°F", "0%"]]
    cols = ["Date", "Conditions", "High/Low", "Precip"]
    sigs = live_data._signals("xweather", rows, cols)
    assert len(sigs) == 1
    assert sigs[0]["kind"] == "DEMAND DIP"
    assert sigs[0]["value"] == 3
    assert "0% precipitation" in sigs[0]["line"]


def test_xweather_wet_day_breaks_the_stretch():
    rows = [["Nov 18", "Sunny", "57°F / 38°F", "0%"],
            ["Nov 19", "Rain", "62°F / 46°F", "80%"],
            ["Nov 20", "Sunny", "60°F / 39°F", "0%"]]
    cols = ["Date", "Conditions", "High/Low", "Precip"]
    assert live_data._signals("xweather", rows, cols) == []


def test_financial_datasets_headlines_become_trend_signals():
    rows = [["Homebuilder confidence sinks", "HousingWire", "2026-11-17"]]
    cols = ["Headline", "Source", "Date"]
    sigs = live_data._signals("financial_datasets", rows, cols)
    assert len(sigs) == 1
    assert sigs[0]["kind"] == "TREND"
    assert "HousingWire" in sigs[0]["line"]


def test_massive_literal_not_entitled_reason():
    assert live_data.MASSIVE_NOT_ENTITLED_REASON == (
        "HTTP 403: not entitled to this data — plan upgrade required"
    )
    card = next(c for c in live_data.cards() if c["id"] == "massive")
    assert card["status"] == live_data.NOT_ENTITLED
    assert card["detail"] == live_data.MASSIVE_NOT_ENTITLED_REASON
    assert card["rows"] == []          # no faked data


def test_needs_key_sources_have_no_rows():
    for card in live_data.cards():
        if card["status"] == live_data.NEEDS_KEY:
            assert card["rows"] == [], card["id"]


def test_live_data_page_serves_signals_and_scheduler(client):
    resp = client.get("/live-data")
    assert resp.status_code == 200
    body = resp.get_data(as_text=True)
    assert "Derived signals" in body
    assert "STALE INVENTORY" in body
    assert "DEMAND DIP" in body
    assert "1GCVKRECXGZ353116" in body          # a real Marketcheck VIN
    assert "not entitled to this data" in body
    assert "In-process scheduler" in body
    assert "not an OS-level supervisor" in body


def test_api_live_data_exposes_signals(client):
    body = client.get("/api/live-data").get_json()
    kinds = {s["kind"] for s in body["signals"]}
    assert {"STALE INVENTORY", "DEMAND DIP", "TREND"} <= kinds
    assert body["stale_dom_days"] == 120


# --------------------------------------------------------------------------
# 2. In-process scheduler loop
# --------------------------------------------------------------------------
def test_loop_status_starts_empty_and_is_not_a_supervisor():
    st = scheduler_loop.status()
    assert st["in_process"] is True
    assert st["os_supervisor"] is False
    assert st["run_count"] == 0
    assert st["last_run_at"] is None
    assert "not" in st["honesty"].lower()


def test_loop_run_once_persists_state_across_reload():
    scheduling.seed_if_empty()
    state = scheduler_loop.run_once(trigger="test")
    assert state["run_count"] == 1
    assert state["last_run_at"]
    # Re-read from the DB (a fresh process would see exactly this).
    st = scheduler_loop.status()
    assert st["run_count"] == 1
    assert st["last_run_at"] == state["last_run_at"]
    assert st["next_run_at"] is not None
    assert st["persisted"] is True
    assert st["last_run_trigger"] == "test"


def test_loop_run_count_is_cumulative():
    scheduler_loop.run_once(trigger="test")
    scheduler_loop.run_once(trigger="test")
    assert scheduler_loop.status()["run_count"] == 2


def test_loop_thread_starts_and_is_alive():
    scheduler_loop.start()
    try:
        assert scheduler_loop.is_running() is True
        assert scheduler_loop.status()["thread_alive"] is True
    finally:
        scheduler_loop.stop()


def test_loop_interval_is_hours():
    assert scheduler_loop.INTERVAL_SECONDS >= 3600


def test_manual_run_route(client):
    resp = client.post("/api/scheduler/loop/run")
    assert resp.status_code == 200
    body = resp.get_json()
    assert body["loop"]["run_count"] == 1
    assert body["loop"]["last_run_trigger"] == "manual"


def test_loop_status_route(client):
    body = client.get("/api/scheduler/loop").get_json()
    assert body["in_process"] is True
    assert body["os_supervisor"] is False


def test_schedules_page_shows_loop_status(client):
    body = client.get("/schedules").get_data(as_text=True)
    assert "In-process scheduler loop" in body
    assert "Run now" in body
    assert "no systemd unit" in body.lower()


# --------------------------------------------------------------------------
# 3. Outreach — KEPT bots, draft only, no send path
# --------------------------------------------------------------------------
def _seed_kept_bot():
    """Insert one KEPT bot spec + decision into the operational DB."""
    from orchestrator.db import connect

    conn = connect()
    try:
        cur = conn.execute(
            "INSERT INTO bot_specs (opportunity_id, spec_json, created_at, spec_hash, status, retired) "
            "VALUES (?,?,?,?,?,0)",
            ("opp-1",
             '{"bot_name":"bot-stale-inventory","purpose":"watches days-on-market per VIN",'
             '"opportunity":{"title":"Stale inventory re-pricing"},'
             '"estimated_monthly_value_usd":900,"estimated_monthly_cost_usd":90,"roi_ratio":10.0,'
             '"requires_human_approval":true,"deployment":{"deployed":false}}',
             "2026-11-18T00:00:00Z", "hash1", "KEPT"),
        )
        bot_id = cur.lastrowid
        conn.execute(
            "INSERT INTO bot_decisions (bot_id, measurement_id, decided_at, rule_version, verdict, "
            "inputs_json, arithmetic_json, reason) VALUES (?,?,?,?,?,?,?,?)",
            (bot_id, 1, "2026-11-18T00:00:00Z", "1.0.0", "KEPT", "{}", "{}",
             "KEEP matched: success_rate 0.95 >= 0.9"),
        )
        conn.commit()
        return bot_id
    finally:
        conn.close()


def test_kept_bots_lists_only_kept():
    bot_id = _seed_kept_bot()
    bots = outreach.kept_bots()
    assert [b["id"] for b in bots] == [bot_id]
    assert bots[0]["verdict"] == "KEPT"


def test_draft_from_kept_bot_is_status_draft():
    bot_id = _seed_kept_bot()
    outreach.seed_if_empty()
    lead = outreach.list_leads()[0]
    draft = outreach.create_draft_from_bot(bot_id, lead["id"])
    assert draft["status"] == "draft"
    assert draft["bot_id"] == bot_id
    assert draft["subject"]
    assert draft["body"]
    assert draft["problem"] == lead["problem"]
    assert draft["approved_at"] is None


def test_draft_requires_explicit_approval():
    bot_id = _seed_kept_bot()
    outreach.seed_if_empty()
    lead = outreach.list_leads()[0]
    draft = outreach.create_draft_from_bot(bot_id, lead["id"])
    approved = outreach.approve_draft(draft["id"], approved_by="operator")
    assert approved["status"] == "approved"
    assert approved["approved_by"] == "operator"


def test_draft_from_non_kept_bot_is_refused():
    from orchestrator.errors import NotFound

    outreach.seed_if_empty()
    lead = outreach.list_leads()[0]
    with pytest.raises(NotFound):
        outreach.create_draft_from_bot(9999, lead["id"])


def test_outreach_module_has_no_send_capability():
    import orchestrator.outreach as mod

    src = open(mod.__file__, encoding="utf-8").read()
    # Only real code counts: the module docstring is allowed to *name* smtplib
    # while explaining that it is not imported.
    code_lines = [ln.strip() for ln in src.splitlines()
                  if ln.strip() and not ln.strip().startswith("#")]
    for forbidden in ("import smtplib", "from smtplib", "import socket", "from socket",
                      "sendmail", "send_message", "requests.post", "urllib.request.urlopen"):
        assert not any(ln.startswith(forbidden) or forbidden in ln
                       for ln in code_lines if not ln.startswith(('"""', "'"))
                       ), forbidden


def test_no_send_routes_registered():
    from app import create_app

    app = create_app(seed=False)
    for rule in app.url_map.iter_rules():
        assert not re.search(r"/send\b", str(rule)), rule
        assert "smtp" not in str(rule).lower(), rule


def test_outreach_snapshot_declares_no_send():
    snap = outreach.snapshot()
    assert snap["send_path"] is None
    assert snap["send_routes"] == []
    assert snap["smtp_configured"] is False
    assert snap["sent_count"] == 0
    assert "Business addresses only" in snap["compliance"]
    assert "No personal addresses" in snap["compliance"]


def test_outreach_page_banner_and_compliance(client):
    body = client.get("/outreach").get_data(as_text=True)
    assert "NOTHING HAS BEEN SENT" in body
    assert "No send capability exists" in body
    assert "business addresses only" in body.lower()
    assert "no personal addresses" in body.lower()
    assert "no SMTP" in body


def test_outreach_page_lists_kept_bots(client):
    _seed_kept_bot()
    body = client.get("/outreach").get_data(as_text=True)
    assert "Draft from a KEPT bot" in body
    assert "bot-stale-inventory" in body
