import ast
import hashlib
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import unittest
from unittest.mock import patch


script_path = Path(sys.argv.pop(1)) if len(sys.argv) > 1 else Path(__file__).with_name("hosyu_post.sh")
source = script_path.read_text(encoding="utf-8").split("tmpRESULT=$(python3 - << 'EOF'", 1)[1].split("\n", 1)[1].split("\nEOF\n", 1)[0]
tree = ast.parse(source)
compile(tree, str(script_path), "exec")
names = {
    "DatPreflightError", "decode_dat_bytes", "looks_like_dat_text",
    "dat_activity_signature", "dat_last_response_unix", "dat_compare_digest",
    "current_dat_state_sync", "md5_current_dat_sync",
}
# Load only DAT helpers; never execute the shell, browser, or posting entry point.
definitions = [node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.ClassDef)) and node.name in names]
namespace = dict(os=os, Path=Path, re=re, subprocess=subprocess, time=time,
                 hashlib=hashlib, th_dir=".", log=lambda message: None)
exec(compile(ast.Module(body=definitions, type_ignores=[]), "dat_helpers", "exec"), namespace)

BASE = "name<>sage<>2026/11/15(\u65e5) 20:02:56.405 ID:test<>test body<>test title\n"


class DatValidationTests(unittest.TestCase):
    validators = ("current_dat_state_sync", "md5_current_dat_sync")

    def call_validator(self, name, text, returncode=0, encoding="cp932"):
        response = subprocess.CompletedProcess(
            args=["curl"], returncode=returncode, stdout=text.encode(encoding),
            stderr=b"HTTP_STATUS:404\n" if returncode else b"HTTP_STATUS:200\n",
        )
        with patch.dict(os.environ, {"CurrentDatURL": "https://example.invalid/thread.dat"}), \
             patch.object(subprocess, "run", return_value=response) as curl, \
             patch.object(Path, "read_bytes", return_value=BASE.encode("cp932")):
            result = namespace[name]()
            curl.assert_called_once()
            self.assertIn("-f", curl.call_args.args[0])
            return result

    def assert_accepted(self, text, encoding="cp932"):
        for name in self.validators:
            with self.subTest(validator=name, text=text, encoding=encoding):
                result = self.call_validator(name, text, encoding=encoding)
                if name == "current_dat_state_sync":
                    self.assertEqual(result["source"], "DAT")
                    self.assertEqual(result["count"], text.count("\n"))
                    self.assertEqual(result["last_unix"], namespace["dat_last_response_unix"](text))
                else:
                    old_digest, new_digest = result
                    self.assertEqual(old_digest, namespace["dat_compare_digest"](BASE))
                    expected = BASE if text.count("\n") == 1 else text
                    self.assertEqual(new_digest, namespace["dat_compare_digest"](expected))

    def test_millisecond_404_is_valid(self):
        self.assert_accepted(BASE.replace(".405", ".404"))

    def test_normal_dat_is_valid(self):
        self.assert_accepted(BASE)

    def test_error_words_in_dat_fields_are_valid(self):
        for token in ("404", "not found", "Not Found"):
            for field in ("name", "ID:test", "test body", "test title"):
                self.assert_accepted(BASE.replace(field, field + " " + token))

    def test_utf8_timestamp_404_is_valid(self):
        self.assert_accepted(BASE.replace(".405", ".404"), encoding="utf-8")

    def test_new_response_with_404_advances_digest_and_count(self):
        self.assert_accepted(BASE + BASE.replace("20:02:56.405", "20:03:56.404"))

    def test_http_404_is_still_rejected(self):
        for name in self.validators:
            with self.subTest(validator=name):
                with self.assertRaisesRegex(namespace["DatPreflightError"], "code=22"):
                    self.call_validator(name, BASE, returncode=22)

    def test_invalid_bodies_are_still_rejected(self):
        for text in ("", " \n", "404 Not Found", "not DAT", "name<>sage<>invalid date<>body<>title",
                     "<html><body>404 Not Found</body></html>", "<html>" + BASE + "</html>"):
            for name in self.validators:
                with self.subTest(validator=name, text=text):
                    with self.assertRaises(namespace["DatPreflightError"]):
                        self.call_validator(name, text)


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