#!/usr/bin/env python3
"""Unit tests for header_lib (run: python3 scripts/test_header_lib.py)."""
from __future__ import annotations

import tempfile
import unittest
from pathlib import Path

from header_lib import (
    apply_header_to_content,
    compute_digest,
    format_identity,
    has_valid_header,
    is_excluded_path,
    parse_identity,
    render_header,
    resolve_header_contributor,
    strip_existing_header,
    build_meta,
)
from pathlib import Path
import header_lib


class HeaderLibTest(unittest.TestCase):
    def test_strip_and_apply_java(self) -> None:
        src = """package com.example;

public class Foo {
}
"""
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "Foo.java"
            path.write_text(src, encoding="utf-8")
            out = apply_header_to_content(path, src)
            self.assertTrue(has_valid_header(out))
            self.assertIn("package com.example;", out)
            self.assertIn(" * class Foo", out)
            self.assertIn("Digest: SHA256", out)
            self.assertIn("Cursor Agent", out)
            body, _ = strip_existing_header(out, ".java")
            self.assertIn("public class Foo", body)
            self.assertNotIn("package com.example", body.split("public class")[0])

    def test_php_header_wrapped_in_comment(self) -> None:
        src = "<?php\ndeclare(strict_types=1);\n"
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "bootstrap.php"
            path.write_text(src, encoding="utf-8")
            out = apply_header_to_content(path, src)
            self.assertTrue(out.startswith("<?php\n/*\n"))
            self.assertIn("*/\ndeclare(strict_types=1)", out)
            self.assertNotIn("?>\n<?php", out)
            self.assertNotIn("/*********************************************************************", out)
            body, _ = strip_existing_header(out, ".php")
            self.assertTrue(body.startswith("declare(strict_types=1)"))

    def test_php_html_template(self) -> None:
        src = "<!DOCTYPE html>\n<html></html>\n"
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "page.php"
            path.write_text(src, encoding="utf-8")
            out = apply_header_to_content(path, src)
            self.assertIn("?>\n<!DOCTYPE", out)
            self.assertNotIn("<?php\n<!DOCTYPE", out)


    def test_commit_excluded_from_digest(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "X.java"
            path.write_text("package p;\npublic class X {}\n", encoding="utf-8")
            body, _ = strip_existing_header(
                apply_header_to_content(path, path.read_text()), ".java")
            meta = build_meta(path, body, path.read_text())
            meta.commit_sha = "aaa"
            d1 = compute_digest(render_header(meta, None, ".java", for_digest=True), body)
            meta.commit_sha = "bbb"
            d2 = compute_digest(render_header(meta, None, ".java", for_digest=True), body)
            self.assertEqual(d1, d2)

    def test_format_identity(self) -> None:
        self.assertEqual("Ada <a@b.c>", format_identity("Ada", "a@b.c"))
        self.assertEqual("Ada", format_identity("Ada", ""))
        name, mail = parse_identity("Ada <a@b.c>")
        self.assertEqual(("Ada", "a@b.c"), (name, mail))

    def test_excluded_third_party(self) -> None:
        p = header_lib.REPO_ROOT / "third-party/libvpx/foo.c"
        self.assertTrue(is_excluded_path(p))

    def test_resolve_header_contributor_env(self) -> None:
        import os
        old = os.environ.get("HEADER_CONTRIBUTOR")
        old_mail = os.environ.get("HEADER_CONTRIBUTOR_EMAIL")
        try:
            os.environ["HEADER_CONTRIBUTOR"] = "Test User"
            os.environ.pop("HEADER_CONTRIBUTOR_EMAIL", None)
            ident = resolve_header_contributor()
            self.assertTrue(ident.startswith("Test User"))
        finally:
            if old is None:
                os.environ.pop("HEADER_CONTRIBUTOR", None)
            else:
                os.environ["HEADER_CONTRIBUTOR"] = old
            if old_mail is None:
                os.environ.pop("HEADER_CONTRIBUTOR_EMAIL", None)
            else:
                os.environ["HEADER_CONTRIBUTOR_EMAIL"] = old_mail


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