"""Keyword-based domain detection — no LLM call, deterministic."""

from pathlib import Path

import structlog

log = structlog.get_logger()

DOMAIN_KEYWORDS: dict[str, list[str]] = {
    "coding": [
        "build",
        "code",
        "implement",
        "refactor",
        "debug",
        "deploy",
        "test",
        "api",
        "database",
        "frontend",
        "backend",
        "server",
        "endpoint",
        "function",
        "class",
        "module",
        "package",
        "library",
        "framework",
        "script",
        "compile",
        "lint",
        "migrate",
        "docker",
        "kubernetes",
        "ci/cd",
        "git",
        "repo",
        "repository",
        "pull request",
        "merge",
        "branch",
    ],
}

# File extensions that boost domain scores
_FILE_TYPE_BOOSTS: dict[str, list[str]] = {
    "coding": [".py", ".ts", ".js", ".go", ".rs", ".java", ".rb", ".cpp", ".c", ".h", ".jsx", ".tsx"],
}

THRESHOLD = 2


def _load_custom_domains(project_root: Path) -> dict[str, list[str]]:
    """Scan .fliiq/playbooks/ for custom playbooks and extract domain keywords."""
    playbooks_dir = project_root / ".fliiq" / "playbooks"
    if not playbooks_dir.is_dir():
        return {}

    custom: dict[str, list[str]] = {}
    for pb in playbooks_dir.glob("*.md"):
        domain = pb.stem
        keywords = [domain]  # Domain name is always a keyword

        # Parse optional "# Keywords:" line from content
        try:
            content = pb.read_text()
            for line in content.split("\n"):
                stripped = line.strip()
                if stripped.lower().startswith("# keywords:"):
                    kw_text = stripped.split(":", 1)[1].strip()
                    keywords.extend(k.strip().lower() for k in kw_text.split(",") if k.strip())
                    break
        except OSError:
            pass

        custom[domain] = keywords
        log.debug("custom_domain_loaded", domain=domain, keywords=keywords)

    return custom


def detect_domain(
    prompt: str, working_dir: Path | None = None, project_root: Path | None = None
) -> list[str]:
    """Return list of detected domains for a given prompt. Threshold=2 keyword matches."""
    prompt_lower = prompt.lower()
    scores: dict[str, int] = {}

    # Merge built-in + custom keywords
    all_keywords: dict[str, list[str]] = dict(DOMAIN_KEYWORDS)
    if project_root:
        all_keywords.update(_load_custom_domains(project_root))

    for domain, keywords in all_keywords.items():
        score = sum(1 for kw in keywords if kw in prompt_lower)
        scores[domain] = score

    # Boost from file types in working directory
    if working_dir and working_dir.is_dir():
        for domain, extensions in _FILE_TYPE_BOOSTS.items():
            for ext in extensions:
                if any(working_dir.glob(f"*{ext}")):
                    scores[domain] = scores.get(domain, 0) + 1
                    break  # One boost per domain from file types

    return [domain for domain, score in scores.items() if score >= THRESHOLD]
