"""Validator parses instruction frontmatter on line 1 (GHI #368).

After GHI #361 moved the do-not-edit banner to immediately after the closing
`---` so Copilot's path-scoped loader sees `applyTo:` on line 1, the surface
validator's pre-strip logic was left targeting the old banner-first layout
and silently removed the entire frontmatter block before parsing — producing
14 spurious "Field required: applyTo" errors against generated mirrors that
do contain `applyTo:`.

These tests pin the post-GHI-#361 layout: when `applyTo:` is present in the
line-1 frontmatter, the validator reports zero errors regardless of whether
the generated banner is present in the body. They also keep the negative
case honest — a mirror that genuinely omits `applyTo:` still surfaces.
"""

import tempfile
import unittest
from pathlib import Path

from gzkit.validate_pkg.surface import _validate_instruction_frontmatter

_FRONTMATTER_FIRST_LAYOUT = (
    "---\n"
    'applyTo: "docs/design/adr/**"\n'
    "---\n"
    "<!-- Generated by gz agent sync — do not edit -->\n"
    "\n"
    "# Sample Instruction\n"
    "\n"
    "Body content.\n"
)


class TestInstructionFrontmatterParsing(unittest.TestCase):
    """`_validate_instruction_frontmatter` reads the line-1 applyTo field."""

    def test_frontmatter_on_line_one_validates_clean(self) -> None:
        with tempfile.TemporaryDirectory() as temp_dir:
            project = Path(temp_dir)
            instructions = project / ".github" / "instructions"
            instructions.mkdir(parents=True)
            (instructions / "sample.instructions.md").write_text(
                _FRONTMATTER_FIRST_LAYOUT, encoding="utf-8"
            )

            errors = _validate_instruction_frontmatter(project)

            self.assertEqual(
                [],
                [(e.artifact, e.message, e.field) for e in errors],
                "frontmatter-first layout must validate without errors",
            )

    def test_missing_applyto_still_surfaces(self) -> None:
        content_without_applyto = (
            "---\n"
            'name: "Sample"\n'
            "---\n"
            "<!-- Generated by gz agent sync — do not edit -->\n"
            "\n"
            "# Sample Instruction\n"
        )
        with tempfile.TemporaryDirectory() as temp_dir:
            project = Path(temp_dir)
            instructions = project / ".github" / "instructions"
            instructions.mkdir(parents=True)
            (instructions / "missing.instructions.md").write_text(
                content_without_applyto, encoding="utf-8"
            )

            errors = _validate_instruction_frontmatter(project)

            applyto_errors = [e for e in errors if e.field == "applyTo"]
            self.assertEqual(
                1,
                len(applyto_errors),
                f"expected one applyTo error; got {[(e.message, e.field) for e in errors]}",
            )


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