"""Direct fixtures, a real stdio suite, and a failing isolated expectation."""
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from validation_server import normalize_label

ROOT = Path(__file__).resolve().parent


class FunctionTests(unittest.TestCase):
    def test_success_fixtures(self):
        cases = [("  Draft  ", 5, {"label": "Draft"}), (" two  words ", 80, {"label": "two  words"}), ("x", 1, {"label": "x"}), ("x" * 80, 80, {"label": "x" * 80})]
        for text, limit, expected in cases:
            with self.subTest(text=text, limit=limit):
                self.assertEqual(normalize_label(text, limit), expected)

    def test_invalid_text_fixtures(self):
        for text, limit in [("   ", 80), ("Draft!", 5), ("xx", 1)]:
            with self.subTest(text=text, limit=limit):
                with self.assertRaisesRegex(ValueError, "after trimming"):
                    normalize_label(text, limit)

    def test_invalid_limit_fixtures(self):
        for limit in [0, -1, 81]:
            with self.subTest(limit=limit):
                with self.assertRaisesRegex(ValueError, "between 1 and 80"):
                    normalize_label("Draft", limit)


class ProtocolTests(unittest.TestCase):
    def test_all_stdio_checks(self):
        result = subprocess.run([sys.executable, str(ROOT / "check_suite.py")], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", timeout=150)
        self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
        self.assertIn("PASS: all five lab checks", result.stdout)

    def test_wrong_expectation_really_fails(self):
        with tempfile.TemporaryDirectory(prefix="label-lab-negative-") as temporary:
            work = Path(temporary)
            for name in ["label_server.py", "lab_session.py", "check_suite.py", "check_stdio.py"]:
                shutil.copyfile(ROOT / name, work / name)
            original = (ROOT / "inspect_contract.py").read_text(encoding="utf-8")
            expectation = 'assert result.structuredContent == {"label": "two  words"}'
            self.assertEqual(original.count(expectation), 1)
            wrong = original.replace(expectation, 'assert result.structuredContent == {"label": "two words"}', 1)
            (work / "inspect_contract.py").write_text(wrong, encoding="utf-8")
            result = subprocess.run([sys.executable, str(work / "check_suite.py")], cwd=work, capture_output=True, text=True, encoding="utf-8", timeout=60)
            self.assertNotEqual(result.returncode, 0)
            self.assertIn("PASS: check_stdio.py", result.stdout)
            self.assertIn("FAIL: inspect_contract.py", result.stdout)
            self.assertIn("AssertionError", result.stderr)
            self.assertNotIn("PASS: check_validation.py", result.stdout)


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