import ast
import contextlib
import io
import os
from pathlib import Path
import re
import sys
import time
import unittest
from unittest.mock import patch


post_path = Path(sys.argv.pop(1))
search_path = Path(sys.argv.pop(1))
post_source = post_path.read_text(encoding="utf-8").split("tmpRESULT=$(python3 - << 'EOF'", 1)[1].split("\n", 1)[1].split("\nEOF\n", 1)[0]
search_source = search_path.read_text(encoding="utf-8").split("ThreadPageInfo=$(python3 - << 'EOF'", 1)[1].split("\n", 1)[1].split("\nEOF\n", 1)[0]
tree = ast.parse(post_source)
compile(tree, str(post_path), "exec")
search_code = compile(search_source, str(search_path), "exec")
definitions = [node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.ClassDef))
               and node.name in {"DatPreflightError", "thread_page_state_from_text"}]
namespace = dict(re=re, time=time)
exec(compile(ast.Module(body=definitions, type_ignores=[]), "page_helpers", "exec"), namespace)

FIRST = "2026/11/29(\u65e5) 21:59:13"
LAST = "2026/11/30(\u6708) 02:59:19"


class ThreadPageDateTests(unittest.TestCase):
    def parse_search(self, html):
        stdout = io.StringIO()
        stderr = io.StringIO()
        with patch.dict(os.environ, {"THDir": "/unused"}), \
             patch.object(Path, "read_bytes", return_value=html.encode("cp932")), \
             patch.object(Path, "write_text") as write, \
             contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
            exec(search_code, {})
            write.assert_called_once()
        count, last_time, last_unix = stdout.getvalue().splitlines()
        return dict(count=int(count), last_time=last_time, last_unix=int(last_unix))

    def assert_dates(self, html):
        expected = dict(count=2, last_time=LAST,
                        last_unix=int(time.mktime(time.strptime("2026/11/30 02:59:19", "%Y/%m/%d %H:%M:%S"))))
        self.assertEqual(namespace["thread_page_state_from_text"](html), expected)
        self.assertEqual(self.parse_search(html), expected)

    def test_legacy_span_dates(self):
        self.assert_dates(f'<span class="date">{FIRST}.855</span><span class="date">{LAST}.343</span>')

    def test_new_time_dates(self):
        self.assert_dates(
            f'<time class="date" itemprop="datePublished" datetime="2026-11-29T21:59:13.855+09:00">{FIRST}.855</time>'
            f'<time class="date" itemprop="datePublished" datetime="2026-11-30T02:59:19.343+09:00">{LAST}.343</time>'
        )

    def test_mixed_tags_and_single_quotes(self):
        self.assert_dates(f"<span class='date'> {FIRST}</span><time class='date'>\n{LAST}</time>")

    def test_hidden_fields_and_quoted_body_dates_are_ignored(self):
        self.assert_dates(
            f'<input name="date" value="{FIRST}.855"><time class="date">{FIRST}</time>'
            f'<input name="date" value="{LAST}.343"><time class="date">{LAST}</time>'
            '<div class="message">2099/01/01(\u6728) 12:34:56</div>'
        )

    def test_missing_response_dates_are_rejected(self):
        for html in ("", "<html><title>Error</title>404</html>",
                     f'<input name="date" value="{LAST}"><div>{LAST}</div>'):
            with self.subTest(html=html):
                with self.assertRaises(namespace["DatPreflightError"]):
                    namespace["thread_page_state_from_text"](html)
                with self.assertRaises(SystemExit) as error:
                    self.parse_search(html)
                self.assertEqual(error.exception.code, 2)


if __name__ == "__main__":
    unittest.main(verbosity=2)
