from __future__ import annotations

import json
from datetime import datetime, timezone

from typer.testing import CliRunner

from eightmem.cli.main import app
from eightmem.core.governance import GovernancePolicy, save_governance_policy
from eightmem.core.heartbeat import run_heartbeat


runner = CliRunner()


def test_heartbeat_reads_file_backed_connectors_and_writes_state(fake_home):
    signals_dir = fake_home / "signals"
    signals_dir.mkdir(parents=True, exist_ok=True)
    (signals_dir / "email_signals.json").write_text(
        json.dumps(
            [
                {
                    "signal_id": "email-1",
                    "source": "email",
                    "title": "Urgent customer email",
                    "summary": "Customer needs a reply today.",
                    "urgency": "high",
                }
            ]
        ),
        encoding="utf-8",
    )
    save_governance_policy(GovernancePolicy())
    result = run_heartbeat(now=datetime(2026, 4, 19, 10, 0, tzinfo=timezone.utc))

    assert result.scanned_signals == 1
    assert len(result.notifications) == 1
    assert result.notifications[0].title == "Urgent customer email"
    assert (fake_home / "heartbeat-state.json").exists()


def test_heartbeat_dedupes_seen_signal_ids(fake_home):
    signals_dir = fake_home / "signals"
    signals_dir.mkdir(parents=True, exist_ok=True)
    (signals_dir / "calendar_signals.json").write_text(
        json.dumps(
            [
                {
                    "signal_id": "cal-1",
                    "source": "calendar",
                    "title": "Meeting in 90 minutes",
                    "summary": "Board prep.",
                    "urgency": "critical",
                }
            ]
        ),
        encoding="utf-8",
    )
    save_governance_policy(GovernancePolicy())

    first = run_heartbeat(now=datetime(2026, 4, 19, 10, 0, tzinfo=timezone.utc))
    second = run_heartbeat(now=datetime(2026, 4, 19, 10, 5, tzinfo=timezone.utc))

    assert len(first.notifications) == 1
    assert len(second.notifications) == 0


def test_heartbeat_cli_reports_notifications(fake_home):
    signals_dir = fake_home / "signals"
    signals_dir.mkdir(parents=True, exist_ok=True)
    (signals_dir / "email_signals.json").write_text(
        json.dumps(
            [
                {
                    "signal_id": "email-2",
                    "source": "email",
                    "title": "Founder inbox",
                    "summary": "Decision needed.",
                    "urgency": "high",
                }
            ]
        ),
        encoding="utf-8",
    )
    save_governance_policy(GovernancePolicy())

    result = runner.invoke(app, ["heartbeat-check", "--now", "2026-04-19T10:00:00+00:00"])

    assert result.exit_code == 0
    assert "Notify now:" in result.stdout
    assert "Founder inbox" in result.stdout
