from __future__ import annotations

import argparse
import json
from pathlib import Path
import sys
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from app.release_metadata import RELEASE  # noqa: E402


PACKAGE_PATHS = (ROOT / "package.json", ROOT / "package-lock.json")


def _read_object(path: Path) -> dict[str, Any]:
    payload = json.loads(path.read_text(encoding="utf-8-sig"))
    if not isinstance(payload, dict):
        raise ValueError(f"Objeto JSON esperado em {path}.")
    return payload


def _mismatches() -> list[str]:
    package = _read_object(PACKAGE_PATHS[0])
    lock = _read_object(PACKAGE_PATHS[1])
    lock_root = lock.get("packages", {}).get("")
    checks = {
        "package.json:version": package.get("version"),
        "package-lock.json:version": lock.get("version"),
        "package-lock.json:packages['']:version": (
            lock_root.get("version") if isinstance(lock_root, dict) else None
        ),
    }
    return [
        f"{field}={actual!r}; esperado {RELEASE.version!r}"
        for field, actual in checks.items()
        if actual != RELEASE.version
    ]


def _write_synced_files() -> None:
    for path in PACKAGE_PATHS:
        payload = _read_object(path)
        payload["version"] = RELEASE.version
        if path.name == "package-lock.json":
            lock_root = payload.get("packages", {}).get("")
            if not isinstance(lock_root, dict):
                raise ValueError("package-lock.json nao possui packages[''] valido.")
            lock_root["version"] = RELEASE.version
        path.write_text(
            json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
            encoding="utf-8",
            newline="\n",
        )


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Sincroniza os espelhos SemVer com frontend/revision.json."
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Somente confere; nao altera arquivos e falha se houver divergencia.",
    )
    args = parser.parse_args()
    mismatches = _mismatches()
    if args.check:
        if mismatches:
            print("Metadados de release divergentes:", file=sys.stderr)
            for mismatch in mismatches:
                print(f"- {mismatch}", file=sys.stderr)
            return 1
        print(
            f"Release conferida: {RELEASE.revision} / {RELEASE.version} / {RELEASE.tag}"
        )
        return 0
    if mismatches:
        _write_synced_files()
        print(f"Espelhos SemVer atualizados para {RELEASE.version}.")
    else:
        print(f"Espelhos SemVer ja estao em {RELEASE.version}.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
