"""Find source files matching a page_id within a project root."""

from __future__ import annotations

import glob
import os
import re


def _to_segments(page_id: str) -> list[str]:
    """Split page_id into meaningful segments (by '-', '_', '/')."""
    return [s for s in re.split(r"[-_/]", page_id) if s]


def _to_camel(segments: list[str]) -> str:
    """Convert segments to CamelCase."""
    return "".join(s.capitalize() for s in segments)


def _to_kebab(segments: list[str]) -> str:
    """Convert segments to kebab-case."""
    return "-".join(s.lower() for s in segments)


def find_source_file(page_id: str, project_root: str) -> list[str]:
    """
    Find source files matching a page_id.

    Strategy:
    1. Try glob with segments joined: **/*seg1*seg2*
    2. Try CamelCase: **/*Seg1Seg2*
    3. Try kebab-case: **/*seg1-seg2*
    4. Try each segment individually if above fails

    Returns list of matching file paths (relative to project_root).
    """
    if not project_root or not os.path.isdir(project_root):
        return []

    segments = _to_segments(page_id)
    if not segments:
        return []

    candidates: set[str] = set()

    # Pattern 1: segments joined with wildcards
    joined_pattern = "*".join(s.lower() for s in segments)
    # Pattern 2: CamelCase
    camel = _to_camel(segments)
    # Pattern 3: kebab-case
    kebab = _to_kebab(segments)

    patterns = [
        f"**/*{joined_pattern}*",
        f"**/*{camel}*",
        f"**/*{kebab}*",
    ]

    for pattern in patterns:
        for match in glob.glob(
            os.path.join(project_root, pattern), recursive=True
        ):
            # Skip node_modules, dist, .git etc.
            rel = os.path.relpath(match, project_root)
            parts = rel.replace("\\", "/").split("/")
            skip_dirs = {"node_modules", "dist", ".git", "__pycache__", ".angular"}
            if any(p in skip_dirs for p in parts):
                continue
            if os.path.isfile(match):
                candidates.add(rel.replace("\\", "/"))

    return sorted(candidates)
