# Tests for iteration 8: task comments (add/list/remove/permissions/count badge/restore) and printable deadline sheet
# Only TEST_ tasks/users are created. Comments + comment history rows of created tasks are removed at teardown.
import json
import re
import uuid

import psycopg
import pytest
import requests

from test_history_reminders import API, ENV, HX, ADMIN, login, ids_for


def db(sql, args=()):
    with psycopg.connect(ENV["DATABASE_URL"], autocommit=True) as c:
        cur = c.execute(sql, args)
        return cur.fetchall() if cur.description else None


@pytest.fixture(scope="module")
def admin():
    return login(*ADMIN)


@pytest.fixture(scope="module")
def ctx(admin):
    d = {"tasks": [], "emails": []}
    yield d
    for t in d["tasks"]:
        admin.delete(f"{API}/tasks/{t}", headers=HX)
    if d["tasks"]:
        db("DELETE FROM task_comments WHERE todo_id = ANY(%s)", (d["tasks"],))
        db("DELETE FROM todo_history WHERE (todo_id = ANY(%s) OR orig_todo_id = ANY(%s)) AND task_title LIKE 'TEST\\_%%'",
           (d["tasks"], d["tasks"]))
    for e in d["emails"]:
        admin.post(f"{API}/admin/revoke", data={"email": e}, allow_redirects=False)


@pytest.fixture(scope="module")
def other(admin, ctx):
    email = f"test_{uuid.uuid4().hex[:8]}@example.com"
    ctx["emails"].append(email)
    assert admin.post(f"{API}/admin/approved", data={"email": email}, allow_redirects=False).status_code == 303
    s = requests.Session()
    r = s.post(f"{API}/register", data={"name": "TEST_Other", "email": email, "password": "TESTpass123"},
               allow_redirects=False)
    assert r.status_code == 303
    return s


def make(s, ctx, **data):
    title = data.setdefault("title", f"TEST_c_{uuid.uuid4().hex[:6]}")
    r = s.post(f"{API}/tasks", data=data, headers=HX)
    assert r.status_code == 200
    ids = ids_for(s, title)
    assert len(ids) == 1
    ctx["tasks"].append(ids[0])
    return ids[0], title


def comment_ids(html):
    return [int(i) for i in re.findall(r'data-testid="comment-(\d+)"', html)]


class TestComments:
    def test_empty_and_validation(self, admin, ctx):
        tid, _ = make(admin, ctx)
        r = admin.get(f"{API}/tasks/{tid}/comments", headers=HX)
        assert r.status_code == 200 and 'data-testid="comments-empty"' in r.text
        r = admin.post(f"{API}/tasks/{tid}/comments", data={"body": "   "}, headers=HX)
        assert 'data-testid="comment-error"' in r.text and "Write a comment first" in r.text
        r = admin.post(f"{API}/tasks/{tid}/comments", data={"body": "x" * 1001}, headers=HX)
        assert 'data-testid="comment-error"' in r.text and "1000" in r.text
        assert db("SELECT count(*) FROM task_comments WHERE todo_id=%s", (tid,))[0][0] == 0

    def test_post_comment_history_badge(self, admin, ctx):
        tid, title = make(admin, ctx)
        r = admin.post(f"{API}/tasks/{tid}/comments", data={"body": "Line one\nLine two"}, headers=HX)
        assert r.status_code == 200
        trig = json.loads(r.headers["HX-Trigger"])
        assert trig.get("commentsChanged") and not trig.get("tasksChanged") and trig.get("historyChanged")
        assert len(comment_ids(r.text)) == 1 and "Line one\nLine two" in r.text and "Admin" in r.text
        assert " NY" in r.text
        h = admin.get(f"{API}/tasks/{tid}/history", headers=HX).text
        assert "Commented:" in h and "Line one" in h
        lst = admin.get(f"{API}/tasks", params={"q": title}, headers=HX).text
        assert f'data-testid="task-comment-count-{tid}"' in lst
        assert re.search(rf'task-comment-count-{tid}"><svg.*?</svg> 1<', lst)
        act = admin.get(f"{API}/tasks", params={"view": "activity"}, headers=HX).text
        assert "Commented:" in act

    def test_remove_permissions(self, admin, other, ctx):
        tid, title = make(admin, ctx)
        r = admin.post(f"{API}/tasks/{tid}/comments", data={"body": "admin note"}, headers=HX)
        admin_cid = comment_ids(r.text)[0]
        r = other.post(f"{API}/tasks/{tid}/comments", data={"body": "other note"}, headers=HX)
        cids = comment_ids(r.text)
        other_cid = [c for c in cids if c != admin_cid][0]
        # other user sees remove only on own comment
        assert f"comment-remove-{other_cid}" in r.text and f"comment-remove-{admin_cid}" not in r.text
        d = other.delete(f"{API}/comments/{admin_cid}", headers=HX)
        assert d.status_code == 403
        # author can remove own
        d = other.delete(f"{API}/comments/{other_cid}", headers=HX)
        assert d.status_code == 200 and other_cid not in comment_ids(d.text)
        # admin can remove anyone's
        r = other.post(f"{API}/tasks/{tid}/comments", data={"body": "other again"}, headers=HX)
        cid2 = [c for c in comment_ids(r.text) if c != admin_cid][0]
        g = admin.get(f"{API}/tasks/{tid}/comments", headers=HX).text
        assert f"comment-remove-{cid2}" in g and f"comment-remove-{admin_cid}" in g
        d = admin.delete(f"{API}/comments/{cid2}", headers=HX)
        assert d.status_code == 200 and "commentsChanged" in d.headers.get("HX-Trigger", "")
        assert admin.delete(f"{API}/comments/{cid2}", headers=HX).status_code == 404
        lst = admin.get(f"{API}/tasks", params={"q": title}, headers=HX).text
        assert re.search(rf'task-comment-count-{tid}"><svg.*?</svg> 1<', lst)
        admin.delete(f"{API}/comments/{admin_cid}", headers=HX)
        lst = admin.get(f"{API}/tasks", params={"q": title}, headers=HX).text
        assert f"task-comment-count-{tid}" not in lst

    def test_survive_delete_restore_and_gone(self, admin, ctx):
        tid, title = make(admin, ctx)
        admin.post(f"{API}/tasks/{tid}/comments", data={"body": "keep me"}, headers=HX)
        assert admin.delete(f"{API}/tasks/{tid}", headers=HX).status_code == 200
        r = admin.post(f"{API}/tasks/{tid}/comments", data={"body": "too late"}, headers=HX)
        assert 'data-testid="task-missing"' in r.text and "deleted by someone else" in r.text
        entry = db("SELECT id FROM todo_history WHERE orig_todo_id=%s AND field='deleted' ORDER BY id DESC", (tid,))[0][0]
        assert admin.post(f"{API}/history/{entry}/restore", headers=HX).status_code == 200
        assert ids_for(admin, title) == [tid]
        g = admin.get(f"{API}/tasks/{tid}/comments", headers=HX).text
        assert "keep me" in g and "too late" not in g

    def test_requires_login(self):
        s = requests.Session()
        for r in (s.get(f"{API}/tasks/1/comments", headers=HX, allow_redirects=False),
                  s.post(f"{API}/tasks/1/comments", data={"body": "x"}, headers=HX, allow_redirects=False),
                  s.delete(f"{API}/comments/1", headers=HX, allow_redirects=False),
                  s.get(f"{API}/print", allow_redirects=False)):
            assert r.status_code in (401, 303, 302, 307), r.status_code


class TestPrint:
    def test_print_filters_order_comments(self, admin, ctx):
        tag = uuid.uuid4().hex[:6]
        a, _ = make(admin, ctx, title=f"TEST_p_{tag}_a", deadline="2031-03-01", color="red", assignee="Ann",
                    matter_no=f"PM-{tag}", notes="note A", hyperlink="https://example.com/a")
        b, _ = make(admin, ctx, title=f"TEST_p_{tag}_b", deadline="2031-01-01", color="green", matter_no=f"PM-{tag}")
        admin.post(f"{API}/tasks/{a}/comments", data={"body": "print comment"}, headers=HX)
        r = admin.get(f"{API}/print", params={"q": f"TEST_p_{tag}"})
        assert r.status_code == 200 and 'data-testid="print-sheet"' in r.text
        assert r.text.index(f"print-row-{b}") < r.text.index(f"print-row-{a}")
        assert re.search(r'data-testid="print-filter">2 tasks', r.text)
        assert "(New York)" in r.text and "note A" in r.text and "https://example.com/a" in r.text
        assert "print comment" not in r.text
        r = admin.get(f"{API}/print", params={"q": f"TEST_p_{tag}", "sort": "deadline", "desc": "1"})
        assert r.text.index(f"print-row-{a}") < r.text.index(f"print-row-{b}")
        r = admin.get(f"{API}/print", params={"matter": f"PM-{tag}", "urgency": "red", "comments": "1"})
        assert f"print-row-{a}" in r.text and f"print-row-{b}" not in r.text
        assert "print comment" in r.text and re.search(r'print-filter">1 task ', r.text)
        assert 'checked' in r.text
        r = admin.get(f"{API}/print", params={"q": f"nomatch_{tag}"})
        assert 'data-testid="print-empty"' in r.text and 'print-filter">0 tasks' in r.text
