"""Platform hook utilities — check-conflict and hook generation."""

from __future__ import annotations

import re
from pathlib import Path

from supermemory.config import get_current_user, memory_root


def check_conflict(file_path: str, root: Path | None = None) -> str | None:
    """Check if a file is claimed in any person's 'DO NOT TOUCH' section.

    Returns a warning string if conflicting, None if clear.
    """
    root = root or memory_root()
    me = get_current_user(root)
    people_dir = root / "people"

    if not people_dir.is_dir():
        return None

    for person_file in people_dir.glob("*.md"):
        if person_file.name.startswith("_"):
            continue

        person_id = person_file.stem
        if person_id == me:
            continue

        claimed_files = _parse_do_not_touch(person_file)
        for claimed in claimed_files:
            if file_path.endswith(claimed) or claimed in file_path:
                return (
                    f"WARNING: {file_path} is claimed by {person_id} "
                    f"in their DO NOT TOUCH section. Coordinate before modifying."
                )

    return None


def _parse_do_not_touch(person_file: Path) -> list[str]:
    """Extract file paths from the 'Working On (DO NOT TOUCH)' section."""
    try:
        text = person_file.read_text()
    except OSError:
        return []

    # Find the DO NOT TOUCH section
    marker = "## Working On (DO NOT TOUCH)"
    idx = text.find(marker)
    if idx == -1:
        return []

    # Get content until next ## heading or end of file
    section = text[idx + len(marker):]
    next_heading = section.find("\n## ")
    if next_heading != -1:
        section = section[:next_heading]

    # Extract backtick-quoted paths from bullet points
    paths = re.findall(r"`([^`]+)`", section)
    return paths
