"""Cargo (Rust) parser — Cargo.toml."""

from __future__ import annotations

from pathlib import Path
from typing import Any


def parse(repo_path: Path) -> dict[str, Any]:
    cargo_toml = repo_path / "Cargo.toml"
    if not cargo_toml.exists():
        return {"found": False, "ecosystem": "crates.io"}

    try:
        import toml
        data = toml.loads(cargo_toml.read_text())
    except Exception:  # noqa: BLE001
        return {"found": False, "ecosystem": "crates.io", "error": "Failed to parse Cargo.toml"}

    deps: list[dict[str, Any]] = []
    for section in ("dependencies", "dev-dependencies", "build-dependencies"):
        for name, spec in data.get(section, {}).items():
            if isinstance(spec, str):
                ver = spec
            elif isinstance(spec, dict):
                ver = spec.get("version", "")
            else:
                ver = ""
            ver_str = str(ver)
            deps.append({
                "name": name,
                "version_spec": ver_str,
                "resolved_version": ver_str.lstrip("^~>=< "),
                "is_direct": True,
                "ecosystem": "crates.io",
            })

    return {
        "found": True,
        "ecosystem": "crates.io",
        "manifest_file": "Cargo.toml",
        "has_lockfile": (repo_path / "Cargo.lock").exists(),
        "lockfile": "Cargo.lock",
        "packages": deps,
    }
