from pathlib import Path

from superyml.core import iter_yaml_files, normalize_yaml_file


def test_iter_yaml_files_filters_extensions(tmp_path: Path) -> None:
    (tmp_path / "a.yaml").write_text("a: 1\n", encoding="utf-8")
    (tmp_path / "b.yml").write_text("b: 2\n", encoding="utf-8")
    (tmp_path / "c.txt").write_text("x", encoding="utf-8")
    (tmp_path / "node_modules").mkdir()
    (tmp_path / "node_modules" / "x.yaml").write_text("a: 1\n", encoding="utf-8")

    files = sorted(p.name for p in iter_yaml_files(tmp_path))
    assert files == ["a.yaml", "b.yml"]


def test_normalize_yaml_file_autofixes(tmp_path: Path) -> None:
    p = tmp_path / "bad.yaml"
    p.write_text("name:   test\nitems:\n  - a\n  -  b", encoding="utf-8")

    result = normalize_yaml_file(p, check_only=False)
    assert result.error is None
    assert result.changed is True
    assert p.read_text(encoding="utf-8").endswith("\n")


def test_normalize_yaml_file_reports_parse_error(tmp_path: Path) -> None:
    p = tmp_path / "broken.yaml"
    p.write_text("key: [1, 2\n", encoding="utf-8")

    result = normalize_yaml_file(p)
    assert result.error is not None
    assert result.changed is False


def test_normalize_yaml_file_recovers_common_top_level_indent_error(tmp_path: Path) -> None:
    p = tmp_path / "storageClass.yaml"
    p.write_text(
        (
            "apiVersion: storage.k8s.io/v1\n"
            "kind: StorageClass\n"
            "metadata:\n"
            "  name: ebs-sc\n"
            "provisioner: ebs.csi.aws.com\n"
            "volumeBindingMode: WaitForFirstConsumer\n"
            "allowVolumeExpansion: true\n"
            "     reclaimPolicy: Retain\n"
        ),
        encoding="utf-8",
    )

    result = normalize_yaml_file(p)
    assert result.error is None
    assert result.changed is True
    assert "reclaimPolicy: Retain\n" in p.read_text(encoding="utf-8")


def test_normalize_yaml_file_recovers_multi_line_weird_indents(tmp_path: Path) -> None:
    p = tmp_path / "storageClass.yaml"
    p.write_text(
        (
            "apiVersion: storage.k8s.io/v1\n"
            "kind: StorageClass\n"
            "metadata:\n"
            "  name: ebs-sc\n"
            "                    provisioner: ebs.csi.aws.com\n"
            "\n"
            "\n"
            "    volumeBindingMode: WaitForFirstConsumer\n"
            "allowVolumeExpansion: true\n"
            "                                                          reclaimPolicy: Retain\n"
        ),
        encoding="utf-8",
    )

    result = normalize_yaml_file(p)
    assert result.error is None
    assert result.changed is True

    fixed = p.read_text(encoding="utf-8")
    assert "provisioner: ebs.csi.aws.com\n" in fixed
    assert "volumeBindingMode: WaitForFirstConsumer\n" in fixed
    assert "reclaimPolicy: Retain\n" in fixed
