from fastapi.testclient import TestClient

from app.main import app
from app.models.event import EventType
from app.repositories.event_store import event_store

client = TestClient(app)


def test_health():
    response = client.get("/health")
    assert response.status_code == 200
    assert response.json()["status"] == "ok"


def test_login_flow():
    r = client.post("/v1/wechat-personal/login/start", json={"account_id": "bot-001", "account_name": "测试号"})
    assert r.status_code == 200
    body = r.json()
    assert body["login_id"]
    assert body["qr_code_url"]

    r = client.get("/v1/wechat-personal/login/bot-001/status")
    assert r.status_code == 200
    assert r.json()["login_status"] == "pending"

    r = client.post("/v1/wechat-personal/login/bot-001/confirm", json={})
    assert r.status_code == 200
    assert r.json()["success"] is True

    r = client.get("/v1/wechat-personal/login/bot-001/status")
    assert r.json()["login_status"] == "success"
    assert r.json()["online_status"] == "online"


def test_send_after_login():
    client.post("/v1/wechat-personal/login/start", json={"account_id": "bot-002"})
    client.post("/v1/wechat-personal/login/bot-002/confirm", json={})

    r = client.post("/v1/wechat-personal/send/text", json={
        "account_id": "bot-002",
        "conversation_id": "room-001",
        "text": "hello",
        "record_id": "rec-001",
    })
    assert r.status_code == 200
    assert r.json()["accepted"] is True
    assert r.json()["message_id"]


def test_send_without_login_fails():
    r = client.post("/v1/wechat-personal/send/text", json={
        "account_id": "bot-offline",
        "conversation_id": "room-001",
        "text": "hello",
        "record_id": "rec-offline",
    })
    assert r.status_code == 200
    assert r.json()["accepted"] is False


def test_heartbeat_and_monitor():
    client.post("/v1/heartbeat", json={"account_id": "bot-003", "risk_level": 10, "sent_count_today": 5})
    r = client.get("/v1/monitor/status")
    assert r.status_code == 200
    clients = r.json()["clients"]
    assert len(clients) >= 1
    assert any(c["account_id"] == "bot-003" and c["risk_level"] == 10 for c in clients)


def test_heartbeat_creates_event():
    event_store.cleanup(0)
    client.post("/v1/heartbeat", json={
        "account_id": "bot-heartbeat",
        "tenant_code": "rescue",
        "risk_level": 10,
        "sent_count_today": 5,
    })
    pending = event_store.fetch_pending(limit=10)
    assert any(e.event_type == EventType.HEARTBEAT and e.tenant_code == "rescue" for e in pending)


def test_monitor_page():
    r = client.get("/monitor")
    assert r.status_code == 200
    assert "channel-status-table" in r.text
