"""Async wiki download task manager.

Each ``pull_wiki`` call creates a background task that downloads wiki pages,
updates the graph, and records progress.  The MCP tool returns immediately
with a ``task_id``; the user polls ``wiki_task_status`` to track progress.

This avoids MCP client timeouts on large kanbans and lets the user observe
progress (and cookie-expiry failures) without blocking the conversation.
"""
from __future__ import annotations

import logging
import threading
import time
import uuid
from dataclasses import dataclass, field
from typing import Any, Callable

logger = logging.getLogger(__name__)

# Task lifecycle states.
STATUS_PENDING = "pending"
STATUS_RUNNING = "running"
STATUS_COMPLETED = "completed"
STATUS_FAILED = "failed"
STATUS_DUPLICATE = "duplicate"  # already downloaded, skipped


@dataclass
class WikiTask:
    """One wiki download task's mutable state."""

    task_id: str
    url: str
    status: str = STATUS_PENDING
    progress: str = ""
    downloaded_files: list[str] = field(default_factory=list)
    graph_updated_files: int = 0
    error: str | None = None
    created_at: float = field(default_factory=time.time)
    started_at: float | None = None
    finished_at: float | None = None

    def to_dict(self) -> dict:
        elapsed = None
        if self.started_at:
            end = self.finished_at or time.time()
            elapsed = round(end - self.started_at, 1)
        return {
            "task_id": self.task_id,
            "url": self.url,
            "status": self.status,
            "progress": self.progress,
            "downloaded_count": len(self.downloaded_files),
            "files": self.downloaded_files[:20],  # cap for response size
            "graph_updated_files": self.graph_updated_files,
            "error": self.error,
            "elapsed_seconds": elapsed,
        }


class WikiTaskManager:
    """Thread-safe registry of wiki download tasks.

    Stored in memory on the ``ProjectBrainServer`` instance.  A serve restart
    loses task history (acceptable — downloaded files persist on disk and in
    the manifest).
    """

    def __init__(self, max_tasks: int = 50):
        self._tasks: dict[str, WikiTask] = {}
        self._lock = threading.Lock()
        self._max_tasks = max_tasks

    def create_task(self, url: str) -> WikiTask:
        """Register a new pending task and return it."""
        task = WikiTask(task_id=uuid.uuid4().hex[:12], url=url)
        with self._lock:
            self._tasks[task.task_id] = task
            self._evict_if_needed()
        return task

    def get_task(self, task_id: str) -> WikiTask | None:
        with self._lock:
            return self._tasks.get(task_id)

    def list_tasks(self, limit: int = 10) -> list[dict]:
        with self._lock:
            tasks = sorted(
                self._tasks.values(),
                key=lambda t: t.created_at,
                reverse=True,
            )[:limit]
            return [t.to_dict() for t in tasks]

    def update_task(self, task_id: str, **kwargs) -> None:
        """Update fields on a task (thread-safe)."""
        with self._lock:
            task = self._tasks.get(task_id)
            if task is None:
                return
            for key, value in kwargs.items():
                if hasattr(task, key):
                    setattr(task, key, value)

    def run_in_background(
        self,
        task: WikiTask,
        fn: Callable[[WikiTask], None],
    ) -> None:
        """Run ``fn(task)`` in a daemon thread.

        ``fn`` is responsible for updating the task's status/progress via
        ``update_task``.  Exceptions are caught and recorded as failures.
        """
        def _wrapper():
            self.update_task(
                task.task_id,
                status=STATUS_RUNNING,
                started_at=time.time(),
            )
            try:
                fn(task)
                # If fn didn't set a terminal status, mark completed.
                current = self.get_task(task.task_id)
                if current and current.status not in (
                    STATUS_COMPLETED, STATUS_FAILED, STATUS_DUPLICATE,
                ):
                    self.update_task(
                        task.task_id,
                        status=STATUS_COMPLETED,
                        finished_at=time.time(),
                    )
            except Exception as exc:
                logger.exception("Wiki task %s failed", task.task_id)
                self.update_task(
                    task.task_id,
                    status=STATUS_FAILED,
                    error=f"{type(exc).__name__}: {exc}",
                    finished_at=time.time(),
                )

        thread = threading.Thread(
            target=_wrapper,
            name=f"wiki-task-{task.task_id}",
            daemon=True,
        )
        thread.start()

    def _evict_if_needed(self) -> None:
        """Keep at most ``max_tasks`` entries (evict oldest)."""
        if len(self._tasks) <= self._max_tasks:
            return
        oldest = sorted(self._tasks.values(), key=lambda t: t.created_at)
        excess = len(self._tasks) - self._max_tasks
        for task in oldest[:excess]:
            self._tasks.pop(task.task_id, None)