# backend/tests/test_api_automation.py — 규칙/제안/로그 API 통합
def test_automation_page_seed(client):
    p = client.get("/api/automation").json()
    assert len(p["rules"]) == 7
    assert sum(1 for r in p["rules"] if r["on"]) == 6  # r6 꺼짐
    assert len(p["suggests"]) == 2 and len(p["log"]) == 6
    assert p["stats"] == {"active": 6, "runs_week": 31, "saved": "1시간 40분"}  # active=켜진 수
    assert len(p["examples"]) == 3


def test_create_rule_fresh(client):
    r = client.post(
        "/api/automation/rules",
        json={
            "name": "출장 전날 저녁 비우기",
            "cat": "cal",
            "trigger": "출장 전날이 되면",
            "cond": "18시 이후 일정이 있으면",
            "action": "다른 날로 옮기자고 제안",
        },
    ).json()
    assert r["fresh"] is True and r["on"] is True and r["last"] == "방금 만듦"
    p = client.get("/api/automation").json()
    assert any(x["name"] == "출장 전날 저녁 비우기" for x in p["rules"])


def test_toggle_rule(client):
    before = client.get("/api/automation").json()["rules"]
    r1 = next(x for x in before if x["id"] == "r1")
    t = client.post("/api/automation/rules/r1/toggle").json()
    assert t["on"] == (not r1["on"])


def test_patch_rule(client):
    t = client.patch("/api/automation/rules/r1", json={"name": "수아 메일 우선"}).json()
    assert t["name"] == "수아 메일 우선"


def test_delete_rule(client):
    assert client.delete("/api/automation/rules/r7").json() == {"deleted": "r7"}
    p = client.get("/api/automation").json()
    assert all(x["id"] != "r7" for x in p["rules"])


def test_accept_suggestion_creates_rule(client):
    r = client.post("/api/automation/suggestions/asug-s1/accept").json()
    assert r["source"] == "suggestion" and r["name"] == "주간 리포트 미리 준비"
    p = client.get("/api/automation").json()
    assert all(g["id"] != "asug-s1" for g in p["suggests"])  # open 목록에서 빠짐


def test_dismiss_suggestion(client):
    client.post("/api/automation/suggestions/asug-s2/dismiss")
    p = client.get("/api/automation").json()
    assert all(g["id"] != "asug-s2" for g in p["suggests"])


def test_parse_endpoint_golden(client):
    r = client.post(
        "/api/automation/parse", json={"text": "뉴스레터는 모아서 저녁에 보여줘"}
    ).json()
    assert r["matched"] and r["cat"] == "mail" and r["parse"]["cond"] is None


def test_trigger_publishes(client):
    r = client.post("/api/automation/trigger", params={"trigger_key": "mail.newsletter"}).json()
    assert r == {"published": "automation.matched", "trigger_key": "mail.newsletter"}


def test_rule_not_found_404(client):
    assert client.post("/api/automation/rules/nope/toggle").status_code == 404
    assert client.post("/api/automation/suggestions/nope/accept").status_code == 404
