"""Config detection module for identifying agent instruction files."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, UTC
import hashlib
from pathlib import Path
from typing import List


@dataclass
class ConfigMetadata:
    """Metadata about detected configuration files."""

    config_source: str  # "default" or "custom"
    config_hash: str  # SHA-256 truncated to 12 chars
    config_files: List[str]  # List of detected files
    captured_at: str  # ISO timestamp


INSTRUCTION_PATTERNS = [
    "CLAUDE.md",  # Claude Code
    ".github/copilot-instructions.md",  # GitHub Copilot
    "AGENTS.md",  # Codex CLI
    "codex.md",  # Codex CLI alt
    "GEMINI.md",  # Gemini CLI
]


def detect_config(workspace_path: Path) -> ConfigMetadata:
    """
    Detect instruction files in the workspace.

    Args:
        workspace_path: Root path to search for instruction files

    Returns:
        ConfigMetadata with detection results
    """
    detected_files: List[str] = []

    for pattern in INSTRUCTION_PATTERNS:
        file_path = workspace_path / pattern
        if file_path.exists():
            detected_files.append(pattern)

    detected_files.sort()
    captured_at = datetime.now(UTC).isoformat().replace("+00:00", "Z")

    if not detected_files:
        return ConfigMetadata(
            config_source="default",
            config_hash="",
            config_files=[],
            captured_at=captured_at,
        )

    combined_content = ""
    for file_name in detected_files:
        file_path = workspace_path / file_name
        combined_content += file_path.read_text(encoding="utf-8")

    full_hash = hashlib.sha256(combined_content.encode("utf-8")).hexdigest()
    truncated_hash = full_hash[:12]

    return ConfigMetadata(
        config_source="custom",
        config_hash=truncated_hash,
        config_files=detected_files,
        captured_at=captured_at,
    )
