"""Live end-to-end smoke check for the personal inbox brief rail."""

from __future__ import annotations

import threading
import sys
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

import brief
import collect
import notify
import rules


def pass_check(name: str, detail: str) -> None:
    print(f"PASS {name}: {detail}")


def collect_with_lock_timeout() -> tuple[collect.Collection, bool]:
    result: dict[str, object] = {}

    def worker() -> None:
        try:
            result["collection"] = collect.collect()
        except Exception as error:
            result["error"] = error

    thread = threading.Thread(target=worker, daemon=True)
    thread.start()
    thread.join(60)
    if thread.is_alive():
        return (
            collect.Collection([], 0, False, datetime.now(timezone.utc).isoformat()),
            True,
        )
    if "error" in result:
        raise result["error"]
    return result["collection"], False

def main() -> int:
    failures: list[str] = []
    smoke_text = "Personal inbox smoke check: Telegram delivery path is working."
    if notify.send(smoke_text):
        pass_check("notify.send", "Telegram API accepted the smoke message")
    else:
        failures.append("notify.send returned False")
        print("FAIL notify.send: Telegram API did not accept the smoke message")

    collection, lock_blocked = collect_with_lock_timeout()
    if not isinstance(collection.messages, list):
        raise AssertionError("collect().messages is not a list")
    if lock_blocked:
        pass_check("collect", "blocked for 60s; treated as concurrent mailbox lock")
    else:
        pass_check(
            "collect",
            f"default 7-day collection returned {len(collection.messages)} messages",
        )

    sample_message = {
        "account": "smoke",
        "message_id": "smoke-rules",
        "from": "Smoke Sender <smoke@example.net>",
        "subject": "Payment due tomorrow",
        "body": "Please review this payment.",
        "attachments": [],
        "date": datetime.now(timezone.utc).isoformat(),
    }
    findings = [rules.classify(sample_message)]
    if not findings or findings[0]["bucket"] != "ACT":
        raise AssertionError("rules did not produce the expected ACT finding")
    pass_check("rules", f"produced {len(findings)} finding with bucket ACT")

    rendered = brief.render(collection, findings, 0)
    if not rendered.strip() or "Covered to " not in rendered:
        raise AssertionError("brief.render did not produce a covered brief")
    pass_check("brief.render", f"rendered {len(rendered.splitlines())} lines")

    if failures:
        print("SMOKE FAIL: " + "; ".join(failures))
        return 1
    print("SMOKE PASS")
    return 0


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