#!/usr/bin/env python3
"""Simple docs lint: verify local markdown links resolve."""

from __future__ import annotations

import re
import sys
from pathlib import Path

LINK_PATTERN = re.compile(r"\[[^\]]+\]\(([^)]+)\)")


def is_external_link(target: str) -> bool:
    lowered = target.lower()
    return lowered.startswith(("http://", "https://", "mailto:"))


def main() -> int:
    root = Path(__file__).resolve().parents[1]
    markdown_files = [root / "README.md", *sorted((root / "docs").glob("*.md"))]
    failures: list[str] = []

    for file_path in markdown_files:
        if not file_path.exists():
            continue
        content = file_path.read_text(encoding="utf-8")
        for match in LINK_PATTERN.finditer(content):
            target = match.group(1).strip()
            if not target or is_external_link(target):
                continue
            target_path = target.split("#", maxsplit=1)[0]
            if not target_path:
                continue
            resolved = (file_path.parent / target_path).resolve()
            if not resolved.exists():
                failures.append(f"{file_path.relative_to(root)} -> missing link target: {target}")

    if failures:
        print("Docs link check failed:")
        for item in failures:
            print(f"- {item}")
        return 1
    print("Docs link check passed")
    return 0


if __name__ == "__main__":
    sys.exit(main())
