"""Smart defaults — auto-detect project, tool, and ticket type from context.

Used by ``proxym do`` and CLI aliases to minimise required arguments.
"""

from __future__ import annotations

import os
from typing import Any


# ── Ticket type detection ────────────────────────────────────

_TYPE_KEYWORDS: dict[str, list[str]] = {
    "bug": ["napraw", "fix", "bug", "crash", "error", "błąd", "broken", "fail"],
    "refactor": [
        "refactor", "podziel", "rozbij", "split", "wydziel", "uprość",
        "simplify", "cleanup", "clean up", "reorganize",
    ],
    "test": ["test", "testy", "pokrycie", "coverage", "spec"],
    "feature": [
        "dodaj", "add", "nowy", "new", "stwórz", "create", "implement",
        "feature", "build",
    ],
}

_TYPE_PRIORITY: dict[str, str] = {
    "bug": "high",
    "feature": "medium",
    "refactor": "medium",
    "test": "low",
    "task": "medium",
}


def detect_ticket_type(task: str) -> str:
    """Guess ticket type from natural-language task description."""
    lower = task.lower()
    for ttype, keywords in _TYPE_KEYWORDS.items():
        if any(kw in lower for kw in keywords):
            return ttype
    return "task"


def default_priority(ticket_type: str) -> str:
    """Return sensible default priority for a ticket type."""
    return _TYPE_PRIORITY.get(ticket_type, "medium")


# ── Tool resolution ──────────────────────────────────────────

_TOOL_HINTS: dict[str, str] = {
    "bug": "aider",
    "fix": "aider",
    "test": "aider",
    "refactor": "claude-code",
    "feature": "claude-code",
    "task": "aider",
}


def resolve_tool(
    ticket_type: str,
    project: dict[str, Any] | None = None,
    explicit: str | None = None,
    project_config: "ProjectConfig | None" = None,
) -> str:
    """Pick the best tool: explicit > .proxym.yaml > project default > type hint."""
    if explicit:
        return explicit
    if project_config and project_config.has_tool:
        return project_config.default_tool
    if project and project.get("default_tool"):
        return project["default_tool"]
    return _TOOL_HINTS.get(ticket_type, "aider")


def resolve_model(
    project: dict[str, Any] | None = None,
    explicit: str | None = None,
    project_config: "ProjectConfig | None" = None,
) -> str:
    """Pick model: explicit > .proxym.yaml > empty (let tool decide)."""
    if explicit:
        return explicit
    if project_config and project_config.has_model:
        return project_config.model
    return ""


def build_context_snippet(project_config: "ProjectConfig | None", project_dir: str = "") -> str:
    """Read context_files from .proxym.yaml and return a markdown snippet for the ticket."""
    if not project_config or not project_config.context_files or not project_dir:
        return ""
    import os
    parts: list[str] = []
    for relpath in project_config.context_files:
        full = os.path.join(project_dir, relpath)
        if os.path.isfile(full):
            try:
                content = open(full, "r", encoding="utf-8", errors="ignore").read()
                if len(content) > 4000:
                    content = content[:4000] + "\n... (truncated)"
                parts.append(f"### {relpath}\n```\n{content}\n```")
            except Exception:
                pass
    if not parts:
        return ""
    return "\n\n---\nContext files:\n\n" + "\n\n".join(parts)


# ── Project resolution ───────────────────────────────────────

def resolve_project(
    projects: list[dict[str, Any]],
    explicit: str | None = None,
) -> dict[str, Any] | None:
    """Find project: explicit name/id → CWD match → single → most recent."""
    if not projects:
        return None

    # 1. Explicit name/id
    if explicit:
        for p in projects:
            if p.get("name") == explicit or p.get("id") == explicit:
                return p
        return None

    # 2. CWD match
    cwd = os.getcwd()
    for p in projects:
        local = p.get("local_path") or p.get("source_path", "")
        if local and cwd.startswith(local):
            return p

    # 3. Single project
    if len(projects) == 1:
        return projects[0]

    # 4. Most recently active
    active = sorted(
        projects,
        key=lambda p: p.get("last_activity") or 0,
        reverse=True,
    )
    return active[0] if active else None
