#!/usr/bin/env python3
"""Generate a PyPI-friendly README from README.md.

This script keeps the source README clean for GitHub while creating
PYPI_README.md with:
1) explicit anchor tags for stable internal fragment links on PyPI
2) absolute GitHub links for relative markdown links
"""

from __future__ import annotations

import re
from pathlib import Path
from typing import Dict

ROOT = Path(__file__).resolve().parent
SOURCE = ROOT / "README.md"
OUTPUT = ROOT / "PYPI_README.md"
GITHUB_BASE = "https://github.com/amplitude/Amplitude/blob/master/langley/amplitude_ai/"

HEADING_RE = re.compile(r"^(#{1,6})\s+(.+?)\s*$")
LINK_RE = re.compile(r"(!?\[[^\]]*])\(([^)]+)\)")
INTERNAL_LINK_RE = re.compile(r"\[[^\]]*]\(#([^)]+)\)")


def slugify_heading(text: str) -> str:
    slug = text.strip().lower()
    slug = re.sub(r"[^\w\- ]", "", slug)
    slug = slug.replace(" ", "-")
    slug = re.sub(r"-{2,}", "-", slug)
    return slug


def to_absolute_link(url: str) -> str:
    if (
        not url
        or url.startswith(("http://", "https://", "#", "mailto:", "data:"))
    ):
        return url

    path_part, sep, fragment = url.partition("#")
    normalized = Path(path_part).as_posix()
    absolute = f"{GITHUB_BASE}{normalized}"
    if sep:
        return f"{absolute}#{fragment}"
    return absolute


def rewrite_links(line: str) -> str:
    def replace_link(match: re.Match[str]) -> str:
        label = match.group(1)
        url = match.group(2).strip()
        return f"{label}({to_absolute_link(url)})"

    return LINK_RE.sub(replace_link, line)


def generate() -> None:
    source_text = SOURCE.read_text(encoding="utf-8")
    heading_counts: Dict[str, int] = {}
    generated_lines: list[str] = []
    in_fence = False
    anchors_added: set[str] = set()

    for line in source_text.splitlines():
        stripped = line.strip()
        if stripped.startswith("```"):
            in_fence = not in_fence
            generated_lines.append(line)
            continue

        if not in_fence:
            match = HEADING_RE.match(line)
            if match:
                heading_text = match.group(2)
                base_slug = slugify_heading(heading_text)
                count = heading_counts.get(base_slug, 0)
                heading_counts[base_slug] = count + 1
                slug = base_slug if count == 0 else f"{base_slug}-{count}"
                generated_lines.append(f'<a id="{slug}"></a>')
                anchors_added.add(slug)

        generated_lines.append(rewrite_links(line))

    generated_text = "\n".join(generated_lines) + "\n"

    fragments = set(INTERNAL_LINK_RE.findall(generated_text))
    missing = sorted(fragment for fragment in fragments if fragment not in anchors_added)
    if missing:
        joined = ", ".join(missing)
        raise ValueError(f"Unresolved internal fragment link(s): {joined}")

    OUTPUT.write_text(generated_text, encoding="utf-8")
    print(f"Wrote {OUTPUT.relative_to(ROOT)}")


if __name__ == "__main__":
    generate()
