"""Data models for Kanban TUI."""

from enum import Enum
from datetime import datetime
from pydantic import BaseModel, Field
import uuid


class ColumnId(str, Enum):
    """Column identifiers for the Kanban board."""
    BACKLOG = "backlog"
    PLANNING = "planning"
    IN_PROGRESS = "in_progress"
    DONE = "done"


class AIStatus(str, Enum):
    """AI execution status for tasks."""
    IDLE = "idle"
    QUEUED = "queued"
    PLANNING = "planning"
    IMPLEMENTING = "implementing"
    REVIEWING = "reviewing"
    COMPLETE = "complete"
    FAILED = "failed"


# Column display configuration
COLUMN_CONFIG = {
    ColumnId.BACKLOG: {"title": "BACKLOG", "icon": "\u2592"},
    ColumnId.PLANNING: {"title": "PLANNING", "icon": "\u25cb"},
    ColumnId.IN_PROGRESS: {"title": "IN PROGRESS", "icon": "\u25d4"},
    ColumnId.DONE: {"title": "DONE", "icon": "\u2713"},
}


class Task(BaseModel):
    """A task on the Kanban board."""

    id: str = Field(default_factory=lambda: str(uuid.uuid4())[:8])
    title: str
    description: str = ""
    column: ColumnId = ColumnId.BACKLOG
    ai_status: AIStatus = AIStatus.IDLE
    created_at: datetime = Field(default_factory=datetime.now)
    updated_at: datetime = Field(default_factory=datetime.now)

    # Planning output
    plan: str | None = None
    plan_steps: list[str] = Field(default_factory=list)
    current_step: int = 0

    # Execution tracking
    files_modified: list[str] = Field(default_factory=list)
    tools_used: int = 0
    thinking_log: list[str] = Field(default_factory=list)
    current_activity: str = ""

    # Results
    summary: str | None = None
    error: str | None = None
    execution_time_seconds: float = 0

    def update(self, **kwargs) -> "Task":
        """Update task fields and timestamp."""
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)
        self.updated_at = datetime.now()
        return self


class Board(BaseModel):
    """The Kanban board containing all tasks."""

    tasks: dict[str, Task] = Field(default_factory=dict)
    column_order: list[ColumnId] = Field(
        default_factory=lambda: [
            ColumnId.BACKLOG,
            ColumnId.PLANNING,
            ColumnId.IN_PROGRESS,
            ColumnId.DONE,
        ]
    )

    def get_tasks_by_column(self, column: ColumnId) -> list[Task]:
        """Get all tasks in a column, sorted by creation date."""
        tasks = [t for t in self.tasks.values() if t.column == column]
        return sorted(tasks, key=lambda t: t.created_at)

    def add_task(self, title: str, description: str = "") -> Task:
        """Add a new task to the backlog."""
        task = Task(title=title, description=description)
        self.tasks[task.id] = task
        return task

    def move_task(self, task_id: str, column: ColumnId) -> Task | None:
        """Move a task to a different column."""
        if task_id in self.tasks:
            task = self.tasks[task_id]
            task.column = column
            task.updated_at = datetime.now()
            return task
        return None

    def update_task(self, task_id: str, **kwargs) -> Task | None:
        """Update a task's fields."""
        if task_id in self.tasks:
            return self.tasks[task_id].update(**kwargs)
        return None

    def delete_task(self, task_id: str) -> bool:
        """Delete a task from the board."""
        if task_id in self.tasks:
            del self.tasks[task_id]
            return True
        return False
