"""Import planfile strategy.yaml into proxym's ticket system.

Converts planfile tasks → proxym tickets with:
- Sprint mapping → proxym sprints
- Task priorities → ticket priorities
- Model hints → execution metadata
- Quality gates → acceptance criteria
"""

from pathlib import Path
from typing import Any

import yaml
import structlog

from proxym.dashboard._tickets_api import _tickets
from proxym.dashboard.tickets import (
    Ticket,
    TicketPriority,
    TicketStatus,
    TicketType,
    Sprint,
    SprintStatus,
)

logger = structlog.get_logger()


def import_strategy(
    strategy_path: str | Path,
    project_name: str,
    *,
    backend: str = "local",
    dry_run: bool = False,
) -> dict:
    """Import strategy.yaml into proxym ticket system.

    Returns:
        {"tickets_created": N, "sprints": [...], "quality_gates": [...]}
    """
    strategy = yaml.safe_load(Path(strategy_path).read_text())
    results = {"tickets_created": 0, "sprints": [], "quality_gates": []}
    
    mgr = _tickets()
    
    # Create or find sprints first
    sprint_map = {}
    for sprint in strategy.get("sprints", []):
        sprint_id = _create_or_get_sprint(mgr, sprint, project_name, dry_run)
        sprint_map[sprint.get("id")] = sprint_id
        
        sprint_tickets = _import_sprint(mgr, sprint, project_name, sprint_id, dry_run)
        results["sprints"].append({
            "id": sprint.get("id"),
            "name": sprint.get("name"),
            "sprint_id": sprint_id,
            "tickets": sprint_tickets,
        })
        results["tickets_created"] += len(sprint_tickets)

    results["quality_gates"] = strategy.get("quality_gates", [])
    logger.info("strategy_imported", 
                strategy_path=strategy_path,
                project=project_name,
                tickets_created=results["tickets_created"],
                sprints=len(results["sprints"]))
    return results


def _create_or_get_sprint(mgr, sprint: dict, project_name: str, dry_run: bool) -> str:
    """Create a sprint in proxym or return existing one."""
    sprint_name = sprint.get("name", f"Sprint {sprint.get('id', 'Unknown')}")
    
    # Check if sprint already exists for this project
    existing_sprints = mgr.list_sprints()
    for existing in existing_sprints:
        if existing.name == sprint_name and existing.goal.startswith(project_name):
            logger.info("sprint_exists", sprint_name=sprint_name, sprint_id=existing.id)
            return existing.id
    
    if dry_run:
        return f"dry-run-{sprint.get('id', 'unknown')}"
    
    # Create new sprint
    new_sprint = Sprint(
        name=sprint_name,
        goal=f"{project_name} - {sprint.get('goal', '')}",
        status=SprintStatus.PLANNING,
        start_date=sprint.get("start_date", ""),
        end_date=sprint.get("end_date", ""),
    )
    created = mgr.create_sprint(new_sprint)
    logger.info("sprint_created", sprint_name=sprint_name, sprint_id=created.id)
    return created.id


def _import_sprint(mgr, sprint: dict, project_name: str, sprint_id: str, dry_run: bool) -> list[dict]:
    """Convert sprint task_patterns to proxym tickets."""
    tickets = []
    for task in sprint.get("task_patterns", []):
        ticket = _task_to_ticket(task, sprint, project_name, sprint_id)
        if not dry_run:
            created = mgr.create_ticket(ticket)
            ticket["ticket_id"] = created.id
        tickets.append(ticket)
    return tickets


def _task_to_ticket(task: dict, sprint: dict, project_name: str, sprint_id: str) -> dict:
    """Map planfile task → proxym ticket."""
    priority_map = {
        "critical": TicketPriority.CRITICAL,
        "high": TicketPriority.HIGH,
        "medium": TicketPriority.MEDIUM,
        "low": TicketPriority.LOW,
    }
    
    type_map = {
        "refactor": TicketType.REFACTOR,
        "feature": TicketType.FEATURE,
        "bug": TicketType.BUG,
        "test": TicketType.TEST,
        "docs": TicketType.DOCS,
        "task": TicketType.TASK,
    }
    
    # Extract model hints as metadata
    model_hints = task.get("model_hints", {})
    
    return {
        "task": task.get("name", "Untitled task"),
        "title": task.get("name", "Untitled task")[:60],
        "project_id": project_name,
        "description": task.get("description", ""),
        "status": TicketStatus.TODO,
        "priority": priority_map.get(task.get("priority", "medium"), TicketPriority.MEDIUM),
        "type": type_map.get(task.get("task_type", "task"), TicketType.TASK),
        "sprint_id": sprint_id,
        "tags": ["planfile"] + task.get("tags", []),
        "files": task.get("files", []),
        "context_files": task.get("context_files", []),
        "depends_on": [],  # Will be resolved later if needed
        "estimated_hours": task.get("estimated_hours", 0),
        "metadata": {
            "source": "planfile",
            "model_hints": model_hints,
            "acceptance_criteria": task.get("acceptance_criteria", []),
            "task_id": task.get("id"),
        }
    }
