# Tests for iteration 2: change history, My tasks filter, urgency counts, reminders toggle, cron reminders, admin email panel
import os
import re
import uuid

import psycopg
import pytest
import requests
from dotenv import dotenv_values

ENV = dotenv_values("/app/backend/.env")


def _base():
    url = os.environ.get("REACT_APP_BACKEND_URL")
    if not url:
        for line in open("/app/frontend/.env"):
            if line.startswith("REACT_APP_BACKEND_URL="):
                url = line.split("=", 1)[1].strip()
    return url.rstrip("/")


API = _base() + "/api"
HX = {"HX-Request": "true"}
ADMIN = ("admin@deadlines.app", "t8PKc104MoJYzpFa")
SECRET = ENV["WEBHOOK_CRON_SECRET"]


def login(email, pw):
    s = requests.Session()
    r = s.post(f"{API}/login", data={"email": email, "password": pw}, allow_redirects=False)
    assert r.status_code == 303
    return s


def ids_for(s, title):
    html = s.get(f"{API}/tasks", params={"q": title}, headers=HX).text
    return [int(i) for i in re.findall(r'data-testid="task-title-(\d+)">' + re.escape(title) + "<", html)]


def counts(html):
    return {k: int(v) for k, v in re.findall(r'data-testid="count-(\w+)">\s*<span class="count-num">(\d+)<', html)}


@pytest.fixture(scope="module")
def admin():
    return login(*ADMIN)


@pytest.fixture(scope="module")
def tracked():
    d = {"tasks": [], "runs": [], "emails": []}
    yield d
    s = login(*ADMIN)
    for t in d["tasks"]:
        s.delete(f"{API}/tasks/{t}", headers=HX)
    for e in d["emails"]:
        s.post(f"{API}/admin/revoke", data={"email": e}, allow_redirects=False)
    if d["runs"]:
        with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
            c.execute("DELETE FROM cron_runs WHERE run_id = ANY(%s)", (d["runs"],))


def make(s, tracked, **data):
    title = data.setdefault("title", f"TEST_h_{uuid.uuid4().hex[:6]}")
    r = s.post(f"{API}/tasks", data=data, headers=HX)
    assert r.status_code == 200 and "tasksChanged" in r.headers.get("HX-Trigger", "")
    ids = ids_for(s, title)
    assert len(ids) == 1
    tracked["tasks"].append(ids[0])
    return ids[0], title


# --- change history ---
class TestHistory:
    def test_create_and_field_changes(self, admin, tracked):
        tid, title = make(admin, tracked, assignee="Bob", matter_no="M1", deadline="2030-01-01", color="green")
        h = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert "Created the task" in h and "Admin" in h
        edit = admin.get(f"{API}/tasks/{tid}/edit", headers=HX).text
        assert 'data-testid="task-history-section"' in edit and 'list="people-list"' in edit
        assert '<datalist id="people-list">' in edit and '<option value="Admin">' in edit
        base = {"title": title, "assignee": "Bob", "matter_no": "M1", "deadline": "2030-01-01", "color": "green",
                "hyperlink": "", "notes": ""}
        # no-change save -> no new entries
        admin.post(f"{API}/tasks/{tid}", data=base, headers=HX)
        h0 = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert h0.count("data-testid=\"history-entry-") == 1
        upd = {**base, "title": title + "x", "assignee": "Carol", "matter_no": "M2", "deadline": "2030-02-02",
               "color": "red", "hyperlink": "example.com", "notes": "first note"}
        admin.post(f"{API}/tasks/{tid}", data=upd, headers=HX)
        tracked_title = title + "x"
        h1 = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert h1.count("data-testid=\"history-entry-") == 8
        for s in ["2030-01-01</span> → <span class=\"new\">2030-02-02", "OK</span> → <span class=\"new\">Urgent non-extendable",
                  "Bob</span> → <span class=\"new\">Carol", "M1</span> → <span class=\"new\">M2",
                  "(blank)</span> → <span class=\"new\">https://example.com", "<b>Task</b>"]:
            assert s in h1, s
        assert re.search(r"<b>Notes</b>\s*added\s*<span class=\"history-notes\">first note", h1)
        # re-save with same normalized hyperlink -> no new entries
        admin.post(f"{API}/tasks/{tid}", data={**upd, "hyperlink": "https://example.com"}, headers=HX)
        assert admin.get(f"{API}/tasks/{tid}/history", headers=HX).text.count("history-entry-") == 8
        admin.post(f"{API}/tasks/{tid}", data={**upd, "hyperlink": "https://example.com", "notes": "second"}, headers=HX)
        admin.post(f"{API}/tasks/{tid}", data={**upd, "hyperlink": "https://example.com", "notes": ""}, headers=HX)
        h2 = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert re.search(r"<b>Notes</b>\s*changed\s*<span class=\"history-notes\">second", h2)
        assert re.search(r"<b>Notes</b>\s*cleared", h2)
        # color endpoint logs; same color doesn't
        admin.post(f"{API}/tasks/{tid}/color", data={"color": "orange"}, headers=HX)
        admin.post(f"{API}/tasks/{tid}/color", data={"color": "orange"}, headers=HX)
        h3 = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert h3.count("history-entry-") == 11
        assert "Urgent non-extendable</span> → <span class=\"new\">Very important" in h3
        # delete removes history
        admin.delete(f"{API}/tasks/{tid}", headers=HX)
        assert ids_for(admin, tracked_title) == []
        assert 'data-testid="history-empty"' in admin.get(f"{API}/tasks/{tid}/history", headers=HX).text

    def test_import_history(self, admin, tracked):
        title = f"TEST_himp_{uuid.uuid4().hex[:6]}"
        r = admin.post(f"{API}/import", files={"file": ("a.csv", f"Task,Urgency\n{title},red\n", "text/csv")}, headers=HX)
        assert 'data-testid="import-count">1<' in r.text
        ids = ids_for(admin, title)
        tracked["tasks"].extend(ids)
        assert "Added the task from a CSV import" in admin.get(f"{API}/tasks/{ids[0]}/history", headers=HX).text

    def test_history_requires_auth(self):
        assert requests.get(f"{API}/tasks/1/history", headers=HX, allow_redirects=False).status_code == 401


# --- My tasks + urgency counts ---
class TestMineCounts:
    def test_mine_and_counts(self, admin, tracked):
        tag = uuid.uuid4().hex[:6]
        a, _ = make(admin, tracked, title=f"TEST_m{tag}_a", assignee="  admin  ", color="red")
        b, _ = make(admin, tracked, title=f"TEST_m{tag}_b", assignee="ADMIN@deadlines.app", color="yellow")
        c, _ = make(admin, tracked, title=f"TEST_m{tag}_c", assignee="Someone", color="red")
        d, _ = make(admin, tracked, title=f"TEST_m{tag}_d", assignee="Admin Jr", color="blue")
        q = f"TEST_m{tag}"
        html = admin.get(f"{API}/tasks", params={"q": q, "mine": "1"}, headers=HX).text
        assert f"TEST_m{tag}_a<" in html and f"TEST_m{tag}_b<" in html
        assert f"TEST_m{tag}_c<" not in html and f"TEST_m{tag}_d<" not in html
        cn = counts(html)
        assert cn == {"all": 2, "red": 1, "orange": 0, "yellow": 1, "blue": 0, "green": 0}, cn
        assert "My tasks</span>" in html
        # counts ignore urgency filter; active chip marked
        html = admin.get(f"{API}/tasks", params={"q": q, "urgency": "red"}, headers=HX).text
        assert counts(html) == {"all": 4, "red": 2, "orange": 0, "yellow": 1, "blue": 1, "green": 0}
        assert 'count-chip chip-red active' in html and f"TEST_m{tag}_b<" not in html
        assert 'count-all active' not in html
        # mine + urgency + sort
        html = admin.get(f"{API}/tasks", params={"q": q, "mine": "1", "urgency": "yellow", "sort": "title", "desc": "1"},
                         headers=HX).text
        assert f"TEST_m{tag}_b<" in html and f"TEST_m{tag}_a<" not in html
        # counts update after change
        admin.post(f"{API}/tasks/{c}/color", data={"color": "green"}, headers=HX)
        assert counts(admin.get(f"{API}/tasks", params={"q": q}, headers=HX).text)["green"] == 1
        # urgency-counts is OOB
        assert 'id="urgency-counts" class="urgency-counts" hx-swap-oob="true"' in html


# --- reminders toggle ---
class TestRemindersToggle:
    def test_toggle_persists(self, admin):
        r = admin.post(f"{API}/me/reminders", data={"enabled": ["0"]})
        assert "reminders-saved" in r.text
        page = admin.get(f"{API}/").text
        assert re.search(r'value="1"\s+data-testid="reminders-toggle"', page)
        admin.post(f"{API}/me/reminders", data={"enabled": ["0", "1"]})
        page = admin.get(f"{API}/").text
        assert re.search(r'value="1" checked data-testid="reminders-toggle"', page)

    def test_toggle_requires_auth(self):
        assert requests.post(f"{API}/me/reminders", data={"enabled": "1"}, allow_redirects=False).status_code == 303


# --- cron endpoint + admin panel ---
class TestCron:
    def test_auth(self):
        assert requests.post(f"{API}/cron/reminders", json={}).status_code == 401
        assert requests.post(f"{API}/cron/reminders", json={}, headers={"Authorization": "Bearer wrong"}).status_code == 401
        assert requests.post(f"{API}/cron/reminders", json={}, 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(f"{API}/cron/reminders", data="not json", headers=h).status_code == 400
        assert requests.post(f"{API}/cron/reminders", json={}, headers=h).status_code == 400

    @pytest.mark.skipif(bool(os.environ.get("SMTP_HOST") or dotenv_values("/app/backend/.env").get("SMTP_HOST")), reason="SMTP configured; would send real email")
    def test_run_and_duplicate(self, admin, tracked):
        rid = f"TEST_run_{uuid.uuid4().hex[:8]}"
        tracked["runs"].append(rid)
        h = {"Authorization": f"Bearer {SECRET}", "X-Webhook-Id": rid}
        r = requests.post(f"{API}/cron/reminders", json={}, headers=h)
        assert r.status_code == 200 and r.json() == {"accepted": True}
        r = requests.post(f"{API}/cron/reminders", json={}, headers=h)
        assert r.status_code == 200 and r.json() == {"accepted": True, "duplicate": True}
        page = admin.get(f"{API}/admin").text
        assert 'data-testid="email-panel"' in page and 'data-testid="smtp-status">Not set up' in page
        assert 'data-testid="last-run"' in page and "Email (SMTP) is not configured" in page
        # run_id from body
        rid2 = f"TEST_run_{uuid.uuid4().hex[:8]}"
        tracked["runs"].append(rid2)
        r = requests.post(f"{API}/cron/reminders", json={"run_id": rid2}, headers={"Authorization": f"Bearer {SECRET}"})
        assert r.json() == {"accepted": True}

    @pytest.mark.skipif(bool(os.environ.get("SMTP_HOST") or dotenv_values("/app/backend/.env").get("SMTP_HOST")), reason="SMTP configured; would send real email")
    def test_test_reminder_no_smtp(self, admin):
        r = admin.post(f"{API}/admin/test-reminder")
        assert r.status_code == 200 and 'data-testid="test-reminder-error"' in r.text

    def test_test_reminder_admin_only(self, tracked):
        email = f"test_{uuid.uuid4().hex[:8]}@example.com"
        admin = login(*ADMIN)
        admin.post(f"{API}/admin/approved", data={"email": email}, allow_redirects=False)
        tracked["emails"].append(email)
        u = requests.Session()
        assert u.post(f"{API}/register", data={"name": "TEST_U", "email": email, "password": "password123"},
                      allow_redirects=False).status_code == 303
        assert u.post(f"{API}/admin/test-reminder", allow_redirects=False).status_code == 403
        # new user appears in datalist
        assert '<option value="TEST_U">' in u.get(f"{API}/tasks/new", headers=HX).text
