"""PROACTIVE OUTREACH - Jarvis speaks first.

Everything in Jarvis so far waits to be asked. The scheduler runs jobs, the
scanner finds opportunities, the outreach engine stages drafts - all of it
responds. Nothing initiates.

This module is the initiating half. It reads what has actually happened, decides
whether any of it is worth interrupting a human about, and says so. It is the
first component whose job is to start a conversation rather than answer one.

The rule
--------
Interruption is expensive, so the bar is named conditions, not "something
happened". Each carries a reason and an urgency:

    chain.broken        critical  the audit chain does not verify
    scan.blackout       high      the last scan fetched nothing
    draft.stalled       high      a draft approved >24h ago and still unsent
    lead.undrafted      normal    a lead with no draft staged
    opportunity.unbuilt normal    a high-score opportunity with no bot spec
    draft.waiting       normal    a draft staged >48h and never approved
    bot.killed          low       the scorecard killed a bot

Only ``normal`` and above interrupt. A killed bot alone is not worth a
notification - it is a line in the next briefing.

What it cannot do
-----------------
It cannot send email. ``orchestrator/outreach.py`` is structurally unable to
transmit and ``tests/test_outreach.py`` enforces that; this module does not
weaken it. Delivery is the ledger row plus, optionally, a local macOS
notification. A real push channel (email/SMS) is the next piece and is not
built.

Read-only except for one ledger row
-----------------------------------
``survey()`` and ``render()`` write nothing. ``initiate()`` writes exactly one
``proactive.initiated`` row and, if asked, fires one local notification.
"""
from __future__ import annotations

import argparse
import json
import shutil
import subprocess
from datetime import datetime, timezone

from . import audit, outreach
from .context import traced

# --- thresholds: named, so they can be argued with -------------------------
STALLED_DRAFT_HOURS = 24
WAITING_DRAFT_HOURS = 48
KILLED_BOT_LOOKBACK_HOURS = 168
UNBUILT_SCORE = 60

#: Lower rank = more urgent. Only ``normal`` and above interrupt.
URGENCY_RANK = {"critical": 0, "high": 1, "normal": 2, "low": 3}
INTERRUPT_AT = URGENCY_RANK["normal"]


# --- small helpers ---------------------------------------------------------
def _now():
    return datetime.now(timezone.utc)


def _field(row, *names, default=None):
    """First present, non-None value among ``names``. Tolerant of shape drift."""
    if not isinstance(row, dict):
        return default
    for name in names:
        if name in row and row[name] is not None:
            return row[name]
    return default


def _parse_ts(value):
    if not value:
        return None
    text = str(value).replace("Z", "+00:00")
    try:
        parsed = datetime.fromisoformat(text)
    except ValueError:
        return None
    return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)


def _age_hours(value, now):
    parsed = _parse_ts(value)
    if parsed is None:
        return None
    if now is None:
        now = _now()
    return (now - parsed).total_seconds() / 3600.0


def _signal(kind, urgency, subject, reason, action=None):
    return {
        "kind": kind,
        "urgency": urgency,
        "subject": subject,
        "reason": reason,
        "action": action,
    }


def _sort_key(signal):
    return (URGENCY_RANK.get(signal["urgency"], 9), signal["kind"], str(signal["subject"]))


# --- the survey: read-only, names what it cannot read ----------------------
def survey(now=None):
    """Every named condition, worst first, plus notes on anything unreadable."""
    now = now or _now()
    found = []
    notes = []

    # 1. the immune system - the only critical condition
    try:
        verdict = audit.verify()
        if not verdict.get("ok"):
            found.append(_signal(
                "chain.broken", "critical", "audit_ledger",
                "the audit chain does not verify: %s" % (verdict.get("detail") or "no detail"),
                "inspect /audit/verify and broken_at",
            ))
    except Exception as exc:
        found.append(_signal(
            "chain.broken", "critical", "audit_ledger",
            "chain verification raised %s: %s" % (type(exc).__name__, exc),
            "the ledger may be unreadable",
        ))

    # 2. the outreach store
    leads, drafts = [], []
    try:
        outreach.init_db()
        leads = outreach.list_leads()
        drafts = outreach.list_drafts()
    except Exception as exc:
        notes.append("outreach store unreadable: %s: %s" % (type(exc).__name__, exc))

    drafted = {_field(d, "lead_id") for d in drafts}
    for lead in leads:
        lead_id = _field(lead, "id")
        if lead_id in drafted:
            continue
        found.append(_signal(
            "lead.undrafted", "normal", "lead:%s" % lead_id,
            "%s (%s, %s) has no draft staged" % (
                _field(lead, "business", default="?"),
                _field(lead, "category", default="?"),
                _field(lead, "city", default="?"),
            ),
            "stage one with outreach.create_draft(%s)" % lead_id,
        ))

    # 3. drafts that are going nowhere
    for draft in drafts:
        draft_id = _field(draft, "id")
        status = str(_field(draft, "status", default="")).lower()
        if status == "approved":
            age = _age_hours(_field(draft, "approved_at", "updated_at", "created_at"), now)
            if age is not None and age >= STALLED_DRAFT_HOURS:
                found.append(_signal(
                    "draft.stalled", "high", "draft:%s" % draft_id,
                    "approved %.0fh ago and still not sent" % age,
                    "copy it into your mail client",
                ))
        elif status == "draft":
            age = _age_hours(_field(draft, "created_at"), now)
            if age is not None and age >= WAITING_DRAFT_HOURS:
                found.append(_signal(
                    "draft.waiting", "normal", "draft:%s" % draft_id,
                    "staged %.0fh ago and never approved" % age,
                    "review it with outreach.approve_draft(%s)" % draft_id,
                ))

    # 4. the keep/kill loop
    try:
        from . import measurement
        decisions = measurement.all_decisions()
        for decision in decisions:
            if str(_field(decision, "verdict", default="")).upper() != "KILLED":
                continue
            age = _age_hours(_field(decision, "created_at", "decided_at"), now)
            if age is None or age > KILLED_BOT_LOOKBACK_HOURS:
                continue
            found.append(_signal(
                "bot.killed", "low", "bot:%s" % _field(decision, "bot_id"),
                "the scorecard killed this bot %.0fh ago" % age,
                "nothing to do - recorded for the record",
            ))
        if decisions:
            notes.append("decisions read: %d" % len(decisions))
    except Exception as exc:
        notes.append("decisions unreadable: %s: %s" % (type(exc).__name__, exc))

    # 5. high-score opportunities the factory has not been given
    try:
        from . import bot_factory
        built = {_field(s, "opportunity_id") for s in bot_factory.list_specs(limit=500)}
    except Exception as exc:
        notes.append("bot specs unreadable: %s: %s" % (type(exc).__name__, exc))
        built = None

    if built is not None:
        try:
            rows = audit.recent(limit=300, action="opportunity.created")
        except Exception as exc:
            notes.append("opportunity rows unreadable: %s: %s" % (type(exc).__name__, exc))
            rows = []
        seen = set()
        for row in rows:
            payload = row.get("payload") if isinstance(row, dict) else None
            if not isinstance(payload, dict):
                continue
            score = payload.get("composite_score")
            opp_id = payload.get("opportunity_id") or (
                row.get("subject_id") if isinstance(row, dict) else None
            )
            if not isinstance(score, (int, float)) or score < UNBUILT_SCORE:
                continue
            if opp_id in built or opp_id in seen:
                continue
            seen.add(opp_id)
            found.append(_signal(
                "opportunity.unbuilt", "normal", "opportunity:%s" % opp_id,
                "scored %.0f and has no bot spec" % score,
                "hand it to the factory",
            ))

    # 6. a scan that fetched nothing
    try:
        runs = audit.recent(limit=5, action="ingest.run")
    except Exception:
        runs = []
    for row in runs[:1]:
        payload = row.get("payload") if isinstance(row, dict) else None
        if not isinstance(payload, dict):
            notes.append("ingest.run payload is not a dict - blackout check skipped")
            break
        total = payload.get("fetched_total")
        errors = payload.get("errors")
        if total == 0 and isinstance(errors, list) and errors:
            found.append(_signal(
                "scan.blackout", "high", "ingest",
                "the last scan fetched nothing and reported %d error(s)" % len(errors),
                "check the source registry and the network",
            ))
        break

    found.sort(key=_sort_key)
    return {
        "checked_at": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
        "signals": found,
        "notes": notes,
    }


def worth_interrupting(report):
    """Only ``normal`` and above. A killed bot alone is not a notification."""
    return [
        s for s in report["signals"]
        if URGENCY_RANK.get(s["urgency"], 9) <= INTERRUPT_AT
    ]


def render(report):
    """The briefing as text. Says so plainly when there is nothing to say."""
    worth = worth_interrupting(report)
    worth_ids = {id(s) for s in worth}
    quiet = [s for s in report["signals"] if id(s) not in worth_ids]

    lines = []
    if worth:
        lines.append("JARVIS - %d thing(s) worth your attention" % len(worth))
        current = None
        for signal in worth:
            if signal["urgency"] != current:
                current = signal["urgency"]
                lines.append("")
                lines.append(current.upper())
            lines.append("  %-20s %s" % (signal["kind"], signal["subject"]))
            lines.append("    %s" % signal["reason"])
            if signal["action"]:
                lines.append("    -> %s" % signal["action"])
    else:
        lines.append("JARVIS - nothing worth interrupting about")

    if quiet:
        lines.append("")
        lines.append("also noted (not interrupting):")
        for signal in quiet:
            lines.append("  %-20s %s  %s" % (signal["kind"], signal["subject"], signal["reason"]))

    if report["notes"]:
        lines.append("")
        lines.append("could not read:")
        for note in report["notes"]:
            lines.append("  %s" % note)

    return "\n".join(lines)


# --- delivery: the ledger always, a local notification on request ----------
def _applescript_string(text):
    return '"%s"' % str(text).replace("\\", "\\\\").replace('"', '\\"')


def notify(title, message):
    """Best-effort local macOS notification. Returns (ok, error). Never raises."""
    if not shutil.which("osascript"):
        return False, "osascript not available (not macOS?)"
    script = "display notification %s with title %s" % (
        _applescript_string(message), _applescript_string(title)
    )
    try:
        subprocess.run(["osascript", "-e", script], check=True,
                       capture_output=True, timeout=10)
        return True, None
    except Exception as exc:
        return False, "%s: %s" % (type(exc).__name__, exc)


# --- dedup: don't re-announce what was already announced -------------------
DEDUP_HOURS = 24

#: read errors from the last dedup pass - surfaced, never swallowed
_DEDUP_ERRORS: list = []


def _recently_announced(now=None):
    """Subjects announced in the last DEDUP_HOURS, read from the ledger.

    Fails open: an unreadable ledger returns an empty set, so the worst case is
    a duplicate announcement rather than silence.
    """
    import json
    now = now or _now()
    try:
        rows = audit.recent(limit=1000, action="proactive.initiated")
    except Exception:
        return set()
    _DEDUP_ERRORS.clear()
    seen = set()
    for row in rows or []:
        try:
            if str(row.get("action", "")) != "proactive.initiated":
                continue
            age = _age_hours(row.get("ts"), now)
            if age is not None and age > DEDUP_HOURS:
                continue
            payload = row.get("payload")
            if isinstance(payload, str):
                payload = json.loads(payload)
            if not isinstance(payload, dict):
                continue
            for subject in payload.get("subjects") or []:
                seen.add(str(subject))
        except Exception as exc:
            if len(_DEDUP_ERRORS) < 5:
                _DEDUP_ERRORS.append("%s: %s" % (type(exc).__name__, exc))
            continue
    return seen


@traced("proactive", "proactive.initiate")
def initiate(channel="ledger", now=None):
    """Decide, record, and optionally say it out loud.

    Writes exactly one ``proactive.initiated`` row when there is something worth
    interrupting about, and nothing at all when there is not.
    """
    report = survey(now)
    worth = worth_interrupting(report)
    text = render(report)

    if not worth:
        return {
            "initiated": False,
            "reason": "nothing worth interrupting about",
            "signals": 0,
            "notes": report["notes"],
            "text": text,
        }

    already = _recently_announced(now)
    if _DEDUP_ERRORS:
        report["notes"] = list(report.get("notes") or []) + [
            "dedup read errors: %s" % "; ".join(_DEDUP_ERRORS)
        ]
    fresh = [s for s in worth if str(s["subject"]) not in already]
    suppressed = len(worth) - len(fresh)

    if not fresh:
        return {
            "initiated": False,
            "reason": "everything already announced",
            "signals": 0,
            "suppressed": suppressed,
            "notes": report["notes"],
            "text": text,
        }

    worth = fresh
    kinds = sorted({s["kind"] for s in worth})
    row = audit.record(
        "proactive",
        "proactive.initiated",
        "briefing",
        subject_id=report["checked_at"],
        payload={
            "signals": len(worth),
            "suppressed": suppressed,
            "kinds": kinds,
            "urgencies": sorted({s["urgency"] for s in worth}),
            "subjects": [s["subject"] for s in worth][:200],
        },
    )

    notified, notify_error = False, None
    if channel == "notify":
        headline = text.splitlines()[0] if text else "briefing"
        notified, notify_error = notify("JARVIS", headline)

    return {
        "initiated": True,
        "signals": len(worth),
        "suppressed": suppressed,
        "kinds": kinds,
        "ledger_seq": row.get("seq") if isinstance(row, dict) else None,
        "notified": notified,
        "notify_error": notify_error,
        "notes": report["notes"],
        "text": text,
    }


def main(argv=None):
    parser = argparse.ArgumentParser(
        prog="jarvis proactive",
        description="Decide whether anything is worth interrupting about.",
    )
    parser.add_argument("--initiate", action="store_true",
                        help="write the ledger row")
    parser.add_argument("--notify", action="store_true",
                        help="also fire a local macOS notification")
    parser.add_argument("--json", action="store_true", help="machine-readable output")
    args = parser.parse_args(argv)

    if args.initiate:
        result = initiate(channel="notify" if args.notify else "ledger")
        if args.json:
            print(json.dumps(result, indent=2, sort_keys=True, default=str))
        else:
            print(result["text"])
            if result["initiated"]:
                print("")
                print("ledger: proactive.initiated (seq %s)" % result["ledger_seq"])
            if result.get("notify_error"):
                print("notify failed: %s" % result["notify_error"])
        return 0

    report = survey()
    if args.json:
        print(json.dumps(report, indent=2, sort_keys=True, default=str))
    else:
        print(render(report))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
