"""Compare versions.lock against installed tools and project versions.env."""

from __future__ import annotations

from pathlib import Path

import click

from anspar_wf.tools.install_tools import TOOL_INSTALLERS, _get_installed_version, parse_versions_lock


def check_versions(versions_lock: Path, versions_env: Path | None = None) -> bool:
    """Check installed tool versions against versions.lock.

    If versions_env is provided, also compare versions.lock against
    the project's .github/versions.env for overlapping keys.

    Returns True if everything matches.
    """
    lock = parse_versions_lock(versions_lock)
    all_ok = True

    click.echo("Checking installed tool versions against versions.lock:")
    for key, (name, _) in TOOL_INSTALLERS.items():
        expected = lock.get(key)
        if not expected:
            continue

        cmd = name.replace("-cli", "")  # markdownlint-cli -> markdownlint
        installed = _get_installed_version(cmd)

        if installed is None:
            click.echo(f"  {name}: NOT INSTALLED (expected {expected})")
            all_ok = False
        elif installed != expected:
            click.echo(f"  {name}: {installed} (expected {expected})")
            all_ok = False
        else:
            click.echo(f"  {name}: {installed} OK")

    # Cross-check with project versions.env
    if versions_env:
        click.echo(f"\nComparing versions.lock with {versions_env}:")
        env = parse_versions_lock(versions_env)  # Same format
        for key in TOOL_INSTALLERS:
            lock_ver = lock.get(key)
            env_ver = env.get(key)
            if lock_ver and env_ver and lock_ver != env_ver:
                name = TOOL_INSTALLERS[key][0]
                click.echo(
                    f"  MISMATCH {name}: "
                    f"versions.lock={lock_ver}, versions.env={env_ver}"
                )
                all_ok = False
            elif lock_ver and env_ver:
                click.echo(f"  {TOOL_INSTALLERS[key][0]}: {lock_ver} (in sync)")

    return all_ok
