"""Sync submodule versions to root pyproject.toml dependencies using uv.

Reads version numbers from submodule pyproject.toml files and updates
the corresponding dependencies in the root pyproject.toml using `uv add`.

Usage:
    uv run scripts/sync_deps.py
"""

import os
import subprocess
import sys

import toml


def get_version_from_pyproject(pyproject_path: str) -> str:
    """Extract version from pyproject.toml.

    Args:
        pyproject_path: Path to pyproject.toml

    Returns:
        Version string

    Raises:
        ValueError: If no version found in pyproject.toml
    """
    with open(pyproject_path, encoding="utf-8") as f:
        data = toml.load(f)

    # Try PEP 621 format first ([project]), then Poetry format ([tool.poetry])
    if "project" in data and "version" in data["project"]:
        return data["project"]["version"]
    elif (
        "tool" in data
        and "poetry" in data["tool"]
        and "version" in data["tool"]["poetry"]
    ):
        return data["tool"]["poetry"]["version"]
    else:
        raise ValueError(f"No version found in {pyproject_path}")


def update_dependency(package_name: str, version: str) -> None:
    """Update a dependency using uv add.

    Args:
        package_name: Name of the package to update
        version: Version constraint to set (e.g., ">=0.2.2")
    """
    cmd = ["uv", "add", f"{package_name}>={version}"]
    print(f"Running: {' '.join(cmd)}")

    result = subprocess.run(cmd, capture_output=True, text=True)

    if result.returncode != 0:
        print(f"Error updating {package_name}: {result.stderr}", file=sys.stderr)
        sys.exit(1)

    print(f"✓ Updated {package_name} to >={version}")


def main() -> None:
    """Update all submodule dependencies in root pyproject.toml."""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.abspath(os.path.join(base_dir, ".."))

    # Submodule configurations: (pyproject_path, package_name)
    submodules = [
        (
            os.path.join(project_root, "authentication", "pyproject.toml"),
            "seven2one-questra-authentication",
        ),
        (
            os.path.join(project_root, "data", "pyproject.toml"),
            "seven2one-questra-data",
        ),
        (
            os.path.join(
                project_root, "automation", "src", "python-client", "pyproject.toml"
            ),
            "seven2one-questra-automation",
        ),
    ]

    print("Syncing submodule versions to root dependencies...\n")

    for pyproject_path, package_name in submodules:
        try:
            version = get_version_from_pyproject(pyproject_path)
            update_dependency(package_name, version)
        except ValueError as e:
            print(f"Error: {e}", file=sys.stderr)
            sys.exit(1)
        except FileNotFoundError:
            print(f"Error: {pyproject_path} not found", file=sys.stderr)
            sys.exit(1)

    print("\n✓ All dependencies synced successfully!")


if __name__ == "__main__":
    main()
