"""Parse @path references in user input for file/directory context injection."""

import re
from dataclasses import dataclass
from pathlib import Path


@dataclass
class AtReference:
    """Parsed @ reference."""

    raw: str  # Original text (e.g., "@src/main.c")
    path: Path  # Resolved absolute path
    exists: bool  # Whether path exists
    is_dir: bool  # True if directory, False if file


def parse_at_references(text: str, project_root: str) -> list[AtReference]:
    """Parse @path references from user input.

    Supports:
        @src/main.c        - relative to project root
        @/opt/sdk/api.h    - absolute path
        @~/projects/lib.c  - home directory
        @./config.toml     - relative to project root
        @../shared/utils.h - parent directory

    Args:
        text: User input text
        project_root: Project root directory path

    Returns:
        List of parsed AtReference objects
    """
    # Match @path preceded by whitespace or at start of string
    # Path continues until delimiter: whitespace, comma, semicolon, etc.
    pattern = r"(?:^|(?<=\s))@([^\s,;!?()\[\]{}]+)"
    matches = re.finditer(pattern, text)

    refs = []
    root = Path(project_root)

    for match in matches:
        raw_path = match.group(1)

        # Resolve path
        if raw_path.startswith("~/"):
            resolved = Path.home() / raw_path[2:]
        elif raw_path.startswith("/"):
            resolved = Path(raw_path)
        else:
            # Relative path (including ./ and ../)
            resolved = (root / raw_path).resolve()

        refs.append(
            AtReference(
                raw=match.group(0),
                path=resolved,
                exists=resolved.exists(),
                is_dir=resolved.is_dir() if resolved.exists() else False,
            )
        )

    return refs


def build_enriched_query(user_input: str, refs: list[AtReference]) -> str:
    """Build enriched query with @ reference instructions.

    Prepends instructions telling AI to read referenced paths.

    Args:
        user_input: Original user input
        refs: Parsed @ references

    Returns:
        Enriched query string
    """
    if not refs:
        return user_input

    lines = [
        "[System: The user referenced the following paths. "
        "Please read them using your Read/Glob tools before responding.]",
    ]

    for ref in refs:
        if not ref.exists:
            lines.append(f"- {ref.path} (NOT FOUND)")
        elif ref.is_dir:
            lines.append(f"- {ref.path} (directory - use Glob or LS to explore)")
        else:
            lines.append(f"- {ref.path} (file)")

    lines.append("")
    lines.append(user_input)

    return "\n".join(lines)
