"""Planner Agent — decides which scanners to run based on the target codebase."""

from __future__ import annotations

import logging
from pathlib import Path

from secagent.llm.grok_client import GrokClient
from secagent.prompts import load as _load_prompt
from secagent.utils.file_loader import collect_files

logger = logging.getLogger(__name__)

_SYSTEM_PROMPT = _load_prompt("planner.txt")


def plan_scan(target: Path, client: GrokClient | None = None) -> list[str]:
    """Analyse *target* and return the list of scanners to run.

    Falls back to running **all** scanners when no LLM is available.
    """
    # Collect basic codebase metadata
    files = collect_files(target)
    extensions = {f.suffix for f in files if f.suffix}
    filenames = {f.name for f in files}

    summary_lines = [
        f"Total files: {len(files)}",
        f"Extensions: {', '.join(sorted(extensions)) or 'none'}",
        f"Notable files: {', '.join(sorted(filenames & _NOTABLE_FILES)) or 'none'}",
    ]
    summary = "\n".join(summary_lines)

    if client and client.api_key:
        result = client.chat(_SYSTEM_PROMPT, summary)
        if isinstance(result, dict) and "scanners" in result:
            scanners = [s for s in result["scanners"] if s in _KNOWN_SCANNERS]
            # Always include built-in scanner and ai-scanner
            if "builtin-secrets" not in scanners:
                scanners.insert(0, "builtin-secrets")
            if "ai-scanner" not in scanners:
                scanners.insert(0, "ai-scanner")
            if scanners:
                logger.info("Planner selected scanners: %s", scanners)
                return scanners

    # Fallback: enable all scanners
    logger.info("Planner fallback: enabling all scanners.")
    return list(_KNOWN_SCANNERS)


_KNOWN_SCANNERS = {"ai-scanner", "builtin-secrets", "gitleaks", "trivy"}

_NOTABLE_FILES = {
    "requirements.txt",
    "Pipfile",
    "pyproject.toml",
    "package.json",
    "yarn.lock",
    "go.mod",
    "Gemfile",
    "pom.xml",
    "build.gradle",
    "Dockerfile",
    "docker-compose.yml",
    ".env",
    "Makefile",
}
