from __future__ import annotations

import difflib
import sys
from pathlib import Path


def normalize(text: str) -> str:
    return text.replace("\r\n", "\n").strip() + "\n"


def assert_same_file(expected: Path, actual: Path) -> None:
    expected_text = normalize(expected.read_text(encoding="utf-8"))
    actual_text = normalize(actual.read_text(encoding="utf-8"))
    if expected_text == actual_text:
        return

    diff = "".join(
        difflib.unified_diff(
            expected_text.splitlines(keepends=True),
            actual_text.splitlines(keepends=True),
            fromfile=str(expected),
            tofile=str(actual),
        )
    )
    raise AssertionError(diff)


def main() -> int:
    project_root = Path(__file__).resolve().parents[1]
    source_config = project_root / "config" / "server.conf"
    build_configs = [
        project_root / "build" / "windows" / "x64" / "debug" / "config" / "server.conf",
        project_root / "build" / "windows" / "x64" / "release" / "config" / "server.conf",
    ]

    missing = [path for path in build_configs if not path.is_file()]
    if missing:
        raise AssertionError(
            "missing build config(s): " + ", ".join(str(path) for path in missing)
        )

    for build_config in build_configs:
        assert_same_file(source_config, build_config)

    print("config sync test passed")
    return 0


if __name__ == "__main__":
    sys.exit(main())
