# Tests for iteration 4: restore deleted tasks (Undo delete), calendar drag-drop deadline move, weekly digest cron contract
# NOTE: real SMTP is configured -> never trigger a non-duplicate cron run with the valid secret, never call /admin/test-digest.
import json
import re
import uuid
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

import psycopg
import pytest
import requests

from test_history_reminders import API, ENV, HX, ADMIN, SECRET, login, ids_for

TODAY = datetime.now(ZoneInfo("America/New_York")).date()
FUT = TODAY + timedelta(days=4)
FUT2 = TODAY + timedelta(days=9)


@pytest.fixture(scope="module")
def admin():
    return login(*ADMIN)


@pytest.fixture(scope="module")
def tracked():
    d = {"tasks": set(), "runs": [], "titles": []}
    yield d
    s = login(*ADMIN)
    with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
        for title in d["titles"]:
            for (tid,) in c.execute("SELECT id FROM todos WHERE title=%s", (title,)).fetchall():
                d["tasks"].add(tid)
    for t in d["tasks"]:
        s.delete(f"{API}/tasks/{t}", headers=HX)
    with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
        if d["titles"]:
            c.execute("DELETE FROM todo_history WHERE task_title = ANY(%s)", (d["titles"],))
        if d["runs"]:
            c.execute("DELETE FROM cron_runs WHERE run_id = ANY(%s)", (d["runs"],))


def make(s, tracked, **data):
    title = data.setdefault("title", f"TEST_r_{uuid.uuid4().hex[:6]}")
    data.setdefault("color", "green")
    r = s.post(f"{API}/tasks", data=data, headers=HX)
    assert r.status_code == 200
    ids = ids_for(s, title)
    assert len(ids) == 1
    tracked["tasks"].add(ids[0])
    tracked["titles"].append(title)
    return ids[0], title


def toast(r):
    return json.loads(r.headers.get("HX-Trigger", "{}")).get("toast")


def deleted_entry(tid):
    with psycopg.connect(ENV["DATABASE_URL"]) as c:
        row = c.execute("SELECT id FROM todo_history WHERE field='deleted' AND orig_todo_id=%s ORDER BY id DESC LIMIT 1",
                        (tid,)).fetchone()
    return row[0] if row else None


def todo(tid):
    with psycopg.connect(ENV["DATABASE_URL"]) as c:
        return c.execute("SELECT title, assignee, matter_no, deadline, color, hyperlink, notes FROM todos WHERE id=%s",
                         (tid,)).fetchone()


# ---------- Restore deleted tasks ----------
class TestRestore:
    def test_delete_restore_full_cycle(self, admin, tracked):
        tid, title = make(admin, tracked, assignee="TEST_ann", matter_no="TEST-M-9", deadline=FUT.isoformat(),
                          color="orange", hyperlink="https://example.com/x", notes="TEST notes\nline2")
        admin.post(f"{API}/tasks/{tid}/color", data={"color": "red"}, headers=HX)
        before = todo(tid)
        r = admin.delete(f"{API}/tasks/{tid}", headers=HX)
        assert r.status_code == 200 and toast(r) == "Task deleted · restore it from the Recycle bin"
        tracked["tasks"].discard(tid)
        assert todo(tid) is None
        eid = deleted_entry(tid)
        assert eid
        html = admin.get(f"{API}/tasks", params={"view": "activity"}, headers=HX).text
        assert f'data-testid="activity-undo-delete-{eid}"' in html
        # restore
        r = admin.post(f"{API}/history/{eid}/restore", headers=HX)
        assert r.status_code == 200 and toast(r) == f"Restored “{title}”"
        tracked["tasks"].add(tid)
        assert todo(tid) == before  # same id, all fields
        html = admin.get(f"{API}/tasks", params={"view": "activity"}, headers=HX).text
        assert f'data-testid="activity-restored-{eid}"' in html
        assert f'activity-undo-delete-{eid}"' not in html
        assert "Restored the task after it was deleted" in html
        hist = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert "Restored the task after it was deleted" in hist and "Created the task" in hist and "Urgency" in hist
        # twice -> no-op
        r = admin.post(f"{API}/history/{eid}/restore", headers=HX)
        assert toast(r) == "This task was already restored"
        assert len(ids_for(admin, title)) == 1

    def test_delete_restore_twice(self, admin, tracked):
        tid, title = make(admin, tracked)
        for _ in range(2):
            admin.delete(f"{API}/tasks/{tid}", headers=HX)
            eid = deleted_entry(tid)
            r = admin.post(f"{API}/history/{eid}/restore", headers=HX)
            assert toast(r).startswith("Restored")
        assert ids_for(admin, title) == [tid]
        hist = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert hist.count("Restored the task after it was deleted") == 2
        assert hist.count("Deleted the task") == 2

    def test_restore_undated_task(self, admin, tracked):
        tid, title = make(admin, tracked)
        admin.delete(f"{API}/tasks/{tid}", headers=HX)
        r = admin.post(f"{API}/history/{deleted_entry(tid)}/restore", headers=HX)
        assert r.status_code == 200 and todo(tid)[3] is None

    def test_restore_non_deleted_entry_noop(self, admin, tracked):
        tid, title = make(admin, tracked)
        with psycopg.connect(ENV["DATABASE_URL"]) as c:
            cid = c.execute("SELECT id FROM todo_history WHERE todo_id=%s AND field='created'", (tid,)).fetchone()[0]
        r = admin.post(f"{API}/history/{cid}/restore", headers=HX)
        assert r.status_code == 200 and toast(r) == "Nothing to restore"
        assert ids_for(admin, title) == [tid]
        r = admin.post(f"{API}/history/999999999/restore", headers=HX)
        assert r.status_code == 200

    def test_restore_requires_login(self):
        r = requests.post(f"{API}/history/1/restore", headers=HX, allow_redirects=False)
        assert r.status_code in (401, 303)
        r = requests.post(f"{API}/history/1/restore", allow_redirects=False)
        assert r.status_code in (401, 303)


# ---------- Drag-and-drop deadline move ----------
class TestMoveDeadline:
    def test_move_and_history(self, admin, tracked):
        tid, title = make(admin, tracked, deadline=FUT.isoformat())
        r = admin.post(f"{API}/tasks/{tid}/deadline", data={"deadline": FUT2.isoformat()}, headers=HX)
        assert r.status_code == 200 and toast(r) == f"Moved “{title}” to {FUT2.strftime('%a %d %b')}"
        assert todo(tid)[3] == FUT2
        hist = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert FUT.isoformat() in hist and FUT2.isoformat() in hist
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": FUT2.strftime("%Y-%m")}, headers=HX).text
        block = html.split(f'data-testid="calendar-day-{FUT2.isoformat()}"', 1)[1].split('role="gridcell"', 1)[0]
        assert f'calendar-task-{tid}"' in block

    def test_same_day_no_history(self, admin, tracked):
        tid, title = make(admin, tracked, deadline=FUT.isoformat())
        with psycopg.connect(ENV["DATABASE_URL"]) as c:
            n0 = c.execute("SELECT count(*) FROM todo_history WHERE todo_id=%s", (tid,)).fetchone()[0]
        r = admin.post(f"{API}/tasks/{tid}/deadline", data={"deadline": FUT.isoformat()}, headers=HX)
        assert r.status_code == 200
        with psycopg.connect(ENV["DATABASE_URL"]) as c:
            n1 = c.execute("SELECT count(*) FROM todo_history WHERE todo_id=%s", (tid,)).fetchone()[0]
        assert n0 == n1

    def test_clear_deadline(self, admin, tracked):
        tid, title = make(admin, tracked, deadline=FUT.isoformat())
        r = admin.post(f"{API}/tasks/{tid}/deadline", data={"deadline": ""}, headers=HX)
        assert r.status_code == 200 and "no deadline" in toast(r)
        assert todo(tid)[3] is None
        html = admin.get(f"{API}/tasks", params={"view": "calendar"}, headers=HX).text
        und = html.split('data-testid="calendar-undated"', 1)[1]
        assert f'calendar-task-{tid}"' in und

    def test_bad_date_and_missing_task_and_auth(self, admin, tracked):
        tid, _ = make(admin, tracked, deadline=FUT.isoformat())
        for bad in ("nonsense", "2026-13-40", "11/12/2026"):
            assert admin.post(f"{API}/tasks/{tid}/deadline", data={"deadline": bad}, headers=HX).status_code == 400
        assert todo(tid)[3] == FUT
        r = admin.post(f"{API}/tasks/999999999/deadline", data={"deadline": FUT.isoformat()}, headers=HX)
        assert r.status_code == 200 and toast(r) == "That task was deleted"
        r = requests.post(f"{API}/tasks/{tid}/deadline", data={"deadline": FUT2.isoformat()}, headers=HX,
                          allow_redirects=False)
        assert r.status_code in (401, 303)
        assert todo(tid)[3] == FUT

    def test_calendar_chips_draggable(self, admin, tracked):
        tid, _ = make(admin, tracked, deadline=FUT.isoformat())
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": FUT.strftime("%Y-%m")}, headers=HX).text
        assert re.search(r'data-task-id="%d" draggable="true"' % tid, html)
        assert "Drag a task to another day" in html


# ---------- Weekly digest cron ----------
class TestDigestCron:
    URL = f"{API}/cron/digest"

    def test_auth(self):
        assert requests.post(self.URL, json={"run_id": "x"}).status_code == 401
        assert requests.post(self.URL, json={"run_id": "x"}, headers={"Authorization": "Bearer wrong"}).status_code == 401
        assert requests.post(self.URL, json={"run_id": "x"}, headers={"Authorization": SECRET}).status_code == 401

    def test_bad_body_and_missing_id(self):
        h = {"Authorization": f"Bearer {SECRET}", "Content-Type": "application/json"}
        assert requests.post(self.URL, data="{bad", headers=h).status_code == 400
        assert requests.post(self.URL, json={}, headers=h).status_code == 400

    def test_duplicate_without_sending_and_admin_panel(self, admin, tracked):
        rid = f"TEST_dig_{uuid.uuid4().hex[:8]}"
        tracked["runs"].append(rid)
        with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
            c.execute("INSERT INTO cron_runs (run_id, kind, sent) VALUES (%s, 'digest', 0)", (rid,))
        r = requests.post(self.URL, headers={"Authorization": f"Bearer {SECRET}", "X-Webhook-Id": rid})
        assert r.status_code == 200 and r.json() == {"accepted": True, "duplicate": True}
        r = requests.post(self.URL, json={"run_id": rid}, headers={"Authorization": f"Bearer {SECRET}"})
        assert r.json() == {"accepted": True, "duplicate": True}
        html = admin.get(f"{API}/admin").text
        assert "Weekly team digest" in html and 'data-testid="test-digest-button"' in html
        assert 'data-testid="last-digest-run"' in html

    def test_test_digest_admin_only(self):
        r = requests.post(f"{API}/admin/test-digest", allow_redirects=False)
        assert r.status_code in (303, 401)

    def test_help_mentions_features(self, admin):
        html = admin.get(f"{API}/").text
        assert "drag a task to another day" in html and "Undo delete" in html and "Weekly digest" in html
