"""Ruby/Bundler parser — Gemfile."""

from __future__ import annotations

import re
from pathlib import Path
from typing import Any


def parse(repo_path: Path) -> dict[str, Any]:
    gemfile = repo_path / "Gemfile"
    if not gemfile.exists():
        return {"found": False, "ecosystem": "RubyGems"}

    deps: list[dict[str, Any]] = []
    for line in gemfile.read_text().splitlines():
        stripped = line.strip()
        if not stripped or stripped.startswith("#"):
            continue
        m = re.match(
            r"""gem\s+['"]([^'"]+)['"]\s*(?:,\s*['"]([^'"]+)['"])?""",
            stripped,
        )
        if m:
            ver_spec = m.group(2) or ""
            deps.append({
                "name": m.group(1),
                "version_spec": ver_spec,
                "resolved_version": re.sub(r"^[~>=<\s]+", "", ver_spec),
                "is_direct": True,
                "ecosystem": "RubyGems",
            })

    return {
        "found": True,
        "ecosystem": "RubyGems",
        "manifest_file": "Gemfile",
        "has_lockfile": (repo_path / "Gemfile.lock").exists(),
        "lockfile": "Gemfile.lock",
        "packages": deps,
    }
