"""Project type detection for TokenGuard.

Detects project type by examining marker files in the target directory.
Also detects whether full GRIP is installed globally and whether
existing hooks are already registered.
"""

import json
from pathlib import Path
from typing import Optional


# Marker files -> project type (checked in order, first match wins)
PROJECT_MARKERS = [
    ("pyproject.toml", "python"),
    ("setup.py", "python"),
    ("setup.cfg", "python"),
    ("requirements.txt", "python"),
    ("Pipfile", "python"),
    ("package.json", "javascript"),
    ("Cargo.toml", "rust"),
    ("go.mod", "go"),
    ("Makefile", "generic"),
]


def detect_project_type(project_dir: Path) -> str:
    """Detect project type from marker files.

    Args:
        project_dir: Root directory of the project.

    Returns:
        Project type string: "python", "javascript", "rust", "go", or "generic".
    """
    for marker_file, project_type in PROJECT_MARKERS:
        if (project_dir / marker_file).exists():
            return project_type
    return "generic"


def detect_grip_global() -> bool:
    """Check if full GRIP is installed globally.

    Looks for ~/.claude/CLAUDE.md containing "GRIP v" to distinguish
    full GRIP installations from bare Claude Code setups.

    Returns:
        True if full GRIP is detected globally.
    """
    claude_md = Path.home() / ".claude" / "CLAUDE.md"
    try:
        if claude_md.exists():
            content = claude_md.read_text(encoding="utf-8")
            return "GRIP v" in content
    except OSError:
        pass
    return False


def detect_existing_hooks(project_dir: Path) -> list:
    """Detect existing PreToolUse hooks in project and global settings.

    Checks both:
    1. {project_dir}/.claude/settings.json
    2. ~/.claude/settings.json (global)

    Returns:
        List of hook command strings found in PreToolUse registrations.
    """
    hooks = []

    settings_paths = [
        project_dir / ".claude" / "settings.json",
        Path.home() / ".claude" / "settings.json",
    ]

    for settings_path in settings_paths:
        try:
            if settings_path.exists():
                settings = json.loads(settings_path.read_text(encoding="utf-8"))
                for group in settings.get("hooks", {}).get("PreToolUse", []):
                    for hook in group.get("hooks", []):
                        cmd = hook.get("command", "")
                        if cmd:
                            hooks.append(cmd)
        except (json.JSONDecodeError, OSError):
            continue

    return hooks


def has_grip_hook(project_dir: Path) -> bool:
    """Check if GRIP's context-gate-hook.py is already registered.

    Returns:
        True if context-gate-hook.py is found in any hook registration.
    """
    hooks = detect_existing_hooks(project_dir)
    return any("context-gate-hook.py" in h for h in hooks)


def detect_existing_mirror(project_dir: Path) -> Optional[dict]:
    """Check if TokenGuard is already initialized in a project.

    Args:
        project_dir: Root directory of the project.

    Returns:
        Parsed .tokenguard.json dict if found, None otherwise.
    """
    mirror_file = project_dir / ".claude" / ".tokenguard.json"
    try:
        if mirror_file.exists():
            return json.loads(mirror_file.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        pass
    return None
