"""Go module parser — go.mod."""

from __future__ import annotations

import re
from pathlib import Path
from typing import Any


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

    deps: list[dict[str, Any]] = []
    in_require_block = False

    for line in go_mod.read_text().splitlines():
        stripped = line.strip()
        if stripped.startswith("require ("):
            in_require_block = True
            continue
        if in_require_block and stripped == ")":
            in_require_block = False
            continue

        content = ""
        if in_require_block:
            content = stripped
        elif stripped.startswith("require ") and "(" not in stripped:
            content = stripped.removeprefix("require ").strip()

        if content and not content.startswith("//"):
            m = re.match(r"^([\w./\-]+)\s+(v[\d.]+(?:-[^\s]+)?)", content)
            if m:
                version = m.group(2)
                deps.append({
                    "name": m.group(1),
                    "version_spec": version,
                    "resolved_version": version.lstrip("v"),
                    "is_direct": True,
                    "ecosystem": "Go",
                })

    return {
        "found": True,
        "ecosystem": "Go",
        "manifest_file": "go.mod",
        "has_lockfile": (repo_path / "go.sum").exists(),
        "lockfile": "go.sum",
        "packages": deps,
    }
