# Regression tests for Shared Deadline List (FastAPI + Jinja2 + HTMX + PostgreSQL), all under /api
import csv
import io
import os
import re
import uuid

import pytest
import requests


def _base():
    url = os.environ.get("REACT_APP_BACKEND_URL")
    if not url:
        with open("/app/frontend/.env") as f:
            for line in f:
                if line.startswith("REACT_APP_BACKEND_URL="):
                    url = line.split("=", 1)[1].strip()
    return url.rstrip("/")


BASE = _base()
API = BASE + "/api"
ADMIN_EMAIL = "admin@deadlines.app"
ADMIN_PASSWORD = "t8PKc104MoJYzpFa"
HX = {"HX-Request": "true"}


def login(email, password):
    s = requests.Session()
    r = s.post(f"{API}/login", data={"email": email, "password": password}, allow_redirects=False)
    return s, r


def task_ids_by_title(session, title):
    html = session.get(f"{API}/tasks", params={"q": title}, headers=HX).text
    ids = re.findall(r'data-testid="task-title-(\d+)">' + re.escape(title) + "<", html)
    return [int(i) for i in ids]


@pytest.fixture(scope="module")
def admin():
    s, r = login(ADMIN_EMAIL, ADMIN_PASSWORD)
    if r.status_code != 303:
        pytest.skip("admin login failed")
    return s


@pytest.fixture(scope="module")
def created_ids():
    return []


@pytest.fixture(scope="module", autouse=True)
def cleanup(created_ids):
    yield
    s, _ = login(ADMIN_EMAIL, ADMIN_PASSWORD)
    for tid in created_ids:
        s.delete(f"{API}/tasks/{tid}", headers=HX)


# --- auth / routing ---
class TestAuth:
    def test_signed_out_redirects(self):
        r = requests.get(f"{API}/", allow_redirects=False)
        assert r.status_code == 303 and r.headers["location"].endswith("/api/login")

    def test_htmx_signed_out_401(self):
        r = requests.get(f"{API}/tasks", headers=HX, allow_redirects=False)
        assert r.status_code == 401
        assert r.headers.get("HX-Redirect") == "/api/login"

    def test_wrong_password(self):
        _, r = login(ADMIN_EMAIL, "wrongpass")
        assert r.status_code == 400
        assert 'data-testid="login-error"' in r.text

    def test_admin_login_and_index(self, admin):
        r = admin.get(f"{API}/")
        assert r.status_code == 200
        assert 'data-testid="admin-link"' in r.text

    def test_export_requires_auth(self):
        r = requests.get(f"{API}/export.csv", allow_redirects=False)
        assert r.status_code == 303


# --- registration / approval / revoke ---
class TestPeople:
    def test_full_registration_flow(self, admin):
        email = f"test_{uuid.uuid4().hex[:8]}@example.com"
        reg = {"name": "TEST_User", "email": email, "password": "password123"}
        # not approved
        r = requests.post(f"{API}/register", data=reg, allow_redirects=False)
        assert r.status_code == 403 and 'data-testid="register-error"' in r.text
        # approve
        r = admin.post(f"{API}/admin/approved", data={"email": email.upper()}, allow_redirects=False)
        assert r.status_code == 303
        assert email in admin.get(f"{API}/admin").text
        # register
        u = requests.Session()
        r = u.post(f"{API}/register", data=reg, allow_redirects=False)
        assert r.status_code == 303 and r.headers["location"].endswith("/api/")
        page = u.get(f"{API}/")
        assert page.status_code == 200 and 'data-testid="admin-link"' not in page.text
        # duplicate
        r = requests.post(f"{API}/register", data=reg, allow_redirects=False)
        assert r.status_code == 400 and "already exists" in r.text
        # non-admin 403
        assert u.get(f"{API}/admin", allow_redirects=False).status_code == 403
        assert u.post(f"{API}/admin/approved", data={"email": "x@y.com"}, allow_redirects=False).status_code == 403
        # updated_by uses name; name change
        r = u.post(f"{API}/me/name", data={"name": "TEST_Renamed"})
        assert r.status_code == 200 and "name-saved" in r.text
        title = f"TEST_byname_{uuid.uuid4().hex[:6]}"
        u.post(f"{API}/tasks", data={"title": title}, headers=HX)
        ids = task_ids_by_title(u, title)
        assert len(ids) == 1
        u.post(f"{API}/tasks/{ids[0]}/color", data={"color": "red"}, headers=HX)
        html = u.get(f"{API}/tasks", params={"q": title}, headers=HX).text
        assert "by TEST_Renamed" in html and "row-red" in html
        u.delete(f"{API}/tasks/{ids[0]}", headers=HX)
        # revoke -> session dead
        r = admin.post(f"{API}/admin/revoke", data={"email": email}, allow_redirects=False)
        assert r.status_code == 303
        assert email not in admin.get(f"{API}/admin").text
        assert u.get(f"{API}/", allow_redirects=False).status_code == 303
        # cannot register after revoke
        r = requests.post(f"{API}/register", data=reg, allow_redirects=False)
        assert r.status_code == 403

    def test_approve_invalid_email(self, admin):
        r = admin.post(f"{API}/admin/approved", data={"email": "notanemail"}, allow_redirects=False)
        assert r.status_code == 400 and 'data-testid="admin-error"' in r.text

    def test_short_password(self, admin):
        r = requests.post(f"{API}/register", data={"name": "x", "email": "a@b.com", "password": "short"},
                          allow_redirects=False)
        assert r.status_code == 400


# --- task CRUD and validation ---
class TestTasks:
    def test_create_validation(self, admin):
        r = admin.post(f"{API}/tasks", data={"title": ""}, headers=HX)
        assert 'data-testid="task-title-error"' in r.text
        for bad in ["javascript:alert(1)", "not a url", "data:text/html,x", "ftp://x.com"]:
            r = admin.post(f"{API}/tasks", data={"title": "TEST_bad", "hyperlink": bad}, headers=HX)
            assert 'data-testid="task-hyperlink-error"' in r.text, bad
        r = admin.post(f"{API}/tasks", data={"title": "TEST_bad", "deadline": "2025/01/01"}, headers=HX)
        assert 'data-testid="task-deadline-error"' in r.text
        assert task_ids_by_title(admin, "TEST_bad") == []

    def test_crud(self, admin, created_ids):
        title = f"TEST_crud_{uuid.uuid4().hex[:6]}"
        r = admin.post(f"{API}/tasks", headers=HX, data={
            "title": title, "assignee": "Bob", "matter_no": "TEST-M-1", "deadline": "2030-01-01",
            "color": "yellow", "hyperlink": "example.com", "notes": "TEST note"})
        assert r.status_code == 200 and "tasksChanged" in r.headers.get("HX-Trigger", "")
        ids = task_ids_by_title(admin, title)
        assert len(ids) == 1
        tid = ids[0]
        created_ids.append(tid)
        html = admin.get(f"{API}/tasks", params={"q": title}, headers=HX).text
        assert 'href="https://example.com"' in html and 'target="_blank"' in html
        assert "row-yellow" in html and "in " in html and "by Admin" in html
        # edit form
        r = admin.get(f"{API}/tasks/{tid}/edit", headers=HX)
        assert "Edit task" in r.text and 'value="2030-01-01"' in r.text
        # update
        r = admin.post(f"{API}/tasks/{tid}", headers=HX, data={"title": title + "_upd", "deadline": "", "color": "blue"})
        assert r.status_code == 200
        html = admin.get(f"{API}/tasks", params={"q": title + "_upd"}, headers=HX).text
        assert "row-blue" in html
        # color invalid
        assert admin.post(f"{API}/tasks/{tid}/color", data={"color": "purple"}, headers=HX).status_code == 400
        # delete
        assert admin.delete(f"{API}/tasks/{tid}", headers=HX).status_code == 200
        assert task_ids_by_title(admin, title + "_upd") == []
        assert "task-missing" in admin.get(f"{API}/tasks/{tid}/edit", headers=HX).text

    def test_filters_and_sort(self, admin, created_ids):
        tag = uuid.uuid4().hex[:6]
        for i, (c, d) in enumerate([("red", "2030-03-01"), ("green", "2030-01-01"), ("blue", "2030-02-01")]):
            admin.post(f"{API}/tasks", headers=HX, data={"title": f"TEST_f{tag}_{i}", "matter_no": f"MX{tag}",
                                                        "color": c, "deadline": d})
        ids = task_ids_by_title(admin, f"TEST_f{tag}_0") + task_ids_by_title(admin, f"TEST_f{tag}_1") + \
            task_ids_by_title(admin, f"TEST_f{tag}_2")
        created_ids.extend(ids)
        assert len(ids) == 3
        html = admin.get(f"{API}/tasks", params={"matter": f"mx{tag}", "urgency": "red"}, headers=HX).text
        assert f"TEST_f{tag}_0" in html and f"TEST_f{tag}_1" not in html
        asc = admin.get(f"{API}/tasks", params={"q": f"TEST_f{tag}", "sort": "deadline", "desc": "0"}, headers=HX).text
        order = re.findall(rf"TEST_f{tag}_(\d)<", asc)
        assert order == ["1", "2", "0"]
        desc = admin.get(f"{API}/tasks", params={"q": f"TEST_f{tag}", "sort": "status", "desc": "1"}, headers=HX).text
        assert re.findall(rf"TEST_f{tag}_(\d)<", desc) == ["0", "2", "1"]
        assert "↓" in desc
        empty = admin.get(f"{API}/tasks", params={"q": "zzz_nomatch_" + tag}, headers=HX).text
        assert "No tasks match" in empty


# --- CSV export/import ---
class TestCsv:
    def test_export_headers(self, admin):
        r = admin.get(f"{API}/export.csv")
        assert r.status_code == 200 and "text/csv" in r.headers["content-type"]
        rows = list(csv.reader(io.StringIO(r.content.decode("utf-8-sig"))))
        assert rows[0] == ["Task", "Assignee", "Matter No", "Deadline", "Urgency", "Hyperlink", "Notes",
                           "Updated At", "Updated By"]

    def test_import(self, admin, created_ids):
        tag = uuid.uuid4().hex[:6]
        content = (
            "Task,Assignee,Matter No,Deadline,Urgency,Hyperlink,Notes\n"
            f"TEST_imp{tag}_a,Ann,M1,2030-05-01,Urgent non-extendable,example.org,n1\n"
            f"TEST_imp{tag}_b,Ben,M2,,yellow,,\n"
            ",x,,,,,\n"
            f"TEST_imp{tag}_c,,,05/01/2030,,,\n"
            f"TEST_imp{tag}_d,,,,,javascript:alert(1),\n"
            f"TEST_imp{tag}_e,,,,purple,,\n"
        )
        r = admin.post(f"{API}/import", files={"file": ("t.csv", content, "text/csv")}, headers=HX)
        assert r.status_code == 200
        assert re.search(r'data-testid="import-count">2<', r.text)
        assert "Row 4" in r.text and "Row 5" in r.text and "Row 6" in r.text and "Row 7" in r.text
        a = task_ids_by_title(admin, f"TEST_imp{tag}_a")
        b = task_ids_by_title(admin, f"TEST_imp{tag}_b")
        created_ids.extend(a + b)
        html = admin.get(f"{API}/tasks", params={"q": f"TEST_imp{tag}"}, headers=HX).text
        assert "row-red" in html and "row-yellow" in html and "https://example.org" in html

        # re-import an exported CSV (only rows of this tag)
        exp = admin.get(f"{API}/export.csv").content.decode("utf-8-sig")
        rows = list(csv.reader(io.StringIO(exp)))
        sub = [rows[0]] + [x for x in rows[1:] if x[0].startswith(f"TEST_imp{tag}")]
        buf = io.StringIO()
        csv.writer(buf).writerows(sub)
        r = admin.post(f"{API}/import", files={"file": ("e.csv", "\ufeff" + buf.getvalue(), "text/csv")}, headers=HX)
        assert re.search(r'data-testid="import-count">2<', r.text) and "import-errors" not in r.text
        a2 = task_ids_by_title(admin, f"TEST_imp{tag}_a")
        b2 = task_ids_by_title(admin, f"TEST_imp{tag}_b")
        created_ids.extend([i for i in a2 + b2 if i not in created_ids])
        assert len(a2) == 2 and len(b2) == 2

    def test_import_no_title_column(self, admin):
        r = admin.post(f"{API}/import", files={"file": ("x.csv", "Name,Deadline\nfoo,2030-01-01\n", "text/csv")},
                       headers=HX)
        assert 'data-testid="import-file-error"' in r.text and "No &#34;Task&#34;" in r.text
