import ast
from pathlib import Path
import subprocess
import unittest
from unittest.mock import patch
from urllib.parse import urlsplit


script = Path(__file__).with_name("hosyu_post.sh").read_text(encoding="utf-8")
python_source = script.split("tmpRESULT=$(python3 - << 'EOF'", 1)[1].split("\n", 1)[1].split("\nEOF\n", 1)[0]
tree = ast.parse(python_source)
compile(tree, "hosyu_post.sh:python", "exec")
selector = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "select_post_proxy")
messages = []
namespace = {"Path": Path, "subprocess": subprocess, "urlsplit": urlsplit, "log": messages.append}
exec(compile(ast.Module(body=[selector], type_ignores=[]), "post_proxy", "exec"), namespace)
select_proxy = namespace["select_post_proxy"]


class ProxySelectionTests(unittest.TestCase):
    def test_disabled_does_not_probe(self):
        with patch.object(Path, "is_file", return_value=False), patch.object(subprocess, "run") as run:
            self.assertIsNone(select_proxy("https://mi.5ch.io/test/read.cgi/news4vip/123/"))
            run.assert_not_called()

    def test_available_uses_wimax_and_probes_without_posting(self):
        with patch.object(Path, "is_file", return_value=True), patch.object(subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as run:
            self.assertEqual(select_proxy("https://mi.5ch.io/test/read.cgi/news4vip/123/"), {"server": "socks5://127.0.0.1:10809"})
            command = run.call_args.args[0]
            self.assertIn("--head", command)
            self.assertEqual(command[-1], "https://mi.5ch.io/")
            self.assertEqual(command[command.index("--noproxy") + 1], "")

    def test_unavailable_uses_normal_connection(self):
        for error in (7, 28, 97):
            with self.subTest(curl_error=error), patch.object(Path, "is_file", return_value=True), patch.object(subprocess, "run", return_value=subprocess.CompletedProcess([], error)):
                self.assertIsNone(select_proxy("https://mi.5ch.io/"))

    def test_probe_timeout_or_missing_command_uses_normal_connection(self):
        for error in (subprocess.TimeoutExpired("curl", 6), FileNotFoundError("curl")):
            with self.subTest(error=type(error).__name__), patch.object(Path, "is_file", return_value=True), patch.object(subprocess, "run", side_effect=error):
                self.assertIsNone(select_proxy("https://mi.5ch.io/"))

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