# Tests for iteration 3: calendar view, activity feed, delete keeps history, overdue cron auth contract, admin overdue panel
# NOTE: real SMTP is configured -> never trigger a non-duplicate cron run with the valid secret.
import re
import uuid
from datetime import date, 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=5)


@pytest.fixture(scope="module")
def admin():
    return login(*ADMIN)


@pytest.fixture(scope="module")
def tracked():
    d = {"tasks": [], "runs": [], "titles": []}
    yield d
    s = login(*ADMIN)
    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_c_{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"].append(ids[0])
    tracked["titles"].append(title)
    return ids[0], title


class TestCalendar:
    def test_default_month_grid(self, admin):
        html = admin.get(f"{API}/tasks", params={"view": "calendar"}, headers=HX).text
        assert 'data-testid="calendar-view"' in html
        assert TODAY.strftime("%B %Y") in html
        assert f'data-testid="calendar-day-{TODAY.isoformat()}"' in html
        assert re.search(r'cal-day[^"]*is-today[^"]*"\s+role="gridcell"(?: data-date="[^"]*")? data-testid="calendar-day-' + TODAY.isoformat(), html)
        assert 'calendar-this-month' not in html
        assert 'data-testid="urgency-counts"' in html
        # Mon first
        dows = re.findall(r'class="cal-dow" role="columnheader">(\w+)<', html)
        assert dows == ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

    def test_task_on_day_and_undated_and_filters(self, admin, tracked):
        tid, title = make(admin, tracked, deadline=FUT.isoformat(), color="blue", assignee="TEST_bob")
        uid, utitle = make(admin, tracked, color="green")
        month = FUT.strftime("%Y-%m")
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": month}, headers=HX).text
        day_block = html.split(f'data-testid="calendar-day-{FUT.isoformat()}"', 1)[1].split('role="gridcell"', 1)[0]
        assert f'data-testid="calendar-task-{tid}"' in day_block
        assert "chip-blue" in day_block
        assert 'data-testid="calendar-undated"' in html and f'calendar-task-{uid}"' in html
        # search filter
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": month, "q": title}, headers=HX).text
        assert f"calendar-task-{tid}" in html and f"calendar-task-{uid}" not in html
        assert "(filtered)" in html and re.search(r'calendar-month-count">[^<]*1 deadline this month', html)
        # urgency filter
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": month, "urgency": "red"}, headers=HX).text
        assert f"calendar-task-{tid}" not in html
        # mine filter (admin is not TEST_bob)
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": month, "mine": "1"}, headers=HX).text
        assert f"calendar-task-{tid}" not in html

    def test_prev_next_and_bad_month(self, admin):
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": "2026-01"}, headers=HX).text
        assert "January 2026" in html and "setMonth('2025-12')" in html and "setMonth('2026-02')" in html
        assert "calendar-this-month" in html
        html = admin.get(f"{API}/tasks", params={"view": "calendar", "month": "2026-12"}, headers=HX).text
        assert "setMonth('2027-01')" in html
        r = admin.get(f"{API}/tasks", params={"view": "calendar", "month": "garbage"}, headers=HX)
        assert r.status_code == 200 and TODAY.strftime("%B %Y") in r.text

    def test_new_prefill(self, admin):
        html = admin.get(f"{API}/tasks/new", params={"deadline": "2026-12-03"}, headers=HX).text
        assert 'value="2026-12-03"' in html
        r = admin.get(f"{API}/tasks/new", params={"deadline": "bad"}, headers=HX)
        assert r.status_code == 200


class TestActivity:
    def test_feed_and_delete_keeps_history(self, admin, tracked):
        tid, title = make(admin, tracked, deadline=FUT.isoformat())
        r = admin.post(f"{API}/tasks/{tid}", data={"title": title, "deadline": FUT.isoformat(), "color": "blue",
                                                   "assignee": "TEST_z"}, headers=HX)
        assert r.status_code == 200
        html = admin.get(f"{API}/tasks", params={"view": "activity"}, headers=HX).text
        assert 'data-testid="activity-view"' in html and title in html
        assert "Created the task" in html and "Not urgent" in html
        assert 'urgency-counts' not in html
        link = re.findall(r'data-testid="activity-task-link-(\d+)">' + re.escape(title), html)
        assert link
        # newest first: Urgency change appears before Created
        seg = html[html.find(title):]
        assert seg.find("Urgency") < seg.find("Created the task")
        # delete -> history kept, deleted entry
        admin.delete(f"{API}/tasks/{tid}", headers=HX)
        tracked["tasks"].remove(tid)
        html = admin.get(f"{API}/tasks", params={"view": "activity"}, headers=HX).text
        assert "Deleted the task" in html
        assert f'feed-task gone">{title}<' in html
        assert not re.search(r'activity-task-link-\d+">' + re.escape(title), html)
        with psycopg.connect(ENV["DATABASE_URL"]) as c:
            n = c.execute("SELECT count(*) FROM todo_history WHERE task_title=%s", (title,)).fetchone()[0]
        assert n >= 3

    def test_other_day_and_who(self, admin):
        html = admin.get(f"{API}/tasks", params={"view": "activity", "day": "2020-01-01"}, headers=HX).text
        assert 'data-testid="activity-empty"' in html and "on this day" in html
        assert "activity-today-button" in html and "setDay('2019-12-31')" in html and "setDay('2020-01-02')" in html
        html = admin.get(f"{API}/tasks", params={"view": "activity", "who": "TEST_nobody"}, headers=HX).text
        assert 'data-testid="activity-empty"' in html and "by TEST_nobody" in html
        r = admin.get(f"{API}/tasks", params={"view": "activity", "day": "nonsense"}, headers=HX)
        assert r.status_code == 200 and "Today" in r.text

    def test_requires_auth(self):
        r = requests.get(f"{API}/tasks", params={"view": "activity"}, headers=HX, allow_redirects=False)
        assert r.status_code == 401


class TestOverdueCron:
    URL = f"{API}/cron/overdue"

    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(self, tracked):
        # pre-claim the run id directly so no background job/email ever runs
        rid = f"TEST_dup_{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, 'overdue', 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}

    def test_admin_panel(self, admin, tracked):
        html = admin.get(f"{API}/admin").text
        assert 'data-testid="check-overdue-button"' in html
        assert 'data-testid="last-overdue-run"' in html  # TEST_dup row exists

    def test_check_overdue_admin_only(self):
        r = requests.post(f"{API}/admin/check-overdue", allow_redirects=False)
        assert r.status_code in (303, 401)
