#!/usr/bin/env python3
"""Generate requirements files for optional extras from uv.lock.

Usage:
    python .github/scripts/sync_requirements.py
"""

from __future__ import annotations

import subprocess
import sys
import tomllib
from pathlib import Path

REPO_ROOT = Path(__file__).parent.parent.parent
REQ_DIR = REPO_ROOT / "agent_cli" / "_requirements"

# Extras to skip (dev/test dependencies, not runtime installable)
SKIP_EXTRAS = {"dev", "test"}


def get_extras() -> list[str]:
    """Parse optional-dependencies from pyproject.toml."""
    pyproject = REPO_ROOT / "pyproject.toml"
    with pyproject.open("rb") as f:
        data = tomllib.load(f)
    all_extras = data.get("project", {}).get("optional-dependencies", {}).keys()
    return [e for e in all_extras if e not in SKIP_EXTRAS]


def _normalize_header(content: str, extra: str) -> str:
    """Replace absolute path in uv header with relative path."""
    lines = content.splitlines(keepends=True)
    # Header has 2 lines: "# This file was autogenerated..." and "#    uv export ..."
    header_lines = 2
    if len(lines) >= header_lines and lines[1].startswith("#    uv export"):
        # Replace the command line with a normalized version (no absolute path)
        lines[1] = f"#    uv export --extra {extra} --no-dev --no-emit-project --no-hashes\n"
    return "".join(lines)


def main() -> None:
    """Generate requirements files from uv.lock."""
    REQ_DIR.mkdir(parents=True, exist_ok=True)
    extras = get_extras()

    for extra in extras:
        print(f"Generating: {extra}")
        output_file = REQ_DIR / f"{extra}.txt"
        cmd = [
            "uv",
            "export",
            "--extra",
            extra,
            "--no-dev",
            "--no-emit-project",
            "--no-hashes",
            "-o",
            str(output_file),
        ]
        result = subprocess.run(cmd, check=False, capture_output=True)
        if result.returncode != 0:
            print(f"Failed to generate {extra}: {result.stderr.decode()}", file=sys.stderr)
            sys.exit(1)

        # Normalize the header to avoid machine-specific paths
        content = output_file.read_text()
        normalized = _normalize_header(content, extra)
        output_file.write_text(normalized)

    print(f"Generated {len(extras)} requirements files")


if __name__ == "__main__":
    main()
