from __future__ import annotations

import json
import uuid
from dataclasses import dataclass
from typing import Any, Dict, List

from core.config import AppConfig
from core.logger import log_error
from core.session import get_session_manager as get_persistent_manager


@dataclass(frozen=True)
class SessionSummary:
    id: str
    title: str
    preview: str
    created_at: str


class SessionManager:
    """Server-side session orchestration.

    Keep listing/preview/persistence concerns in one place.
    HTTP /sessions and WS handlers should use this as the source of truth.

    NOTE: This manager currently focuses on persistent session listing.
    In-memory WS session objects are still managed by ConnectionSessionManager.
    """

    def __init__(self, config: AppConfig):
        self._config = config
        self._persistent_mgr = get_persistent_manager()

    def is_session_id_valid(self, session_id: str) -> bool:
        """Basic sanity check to prevent creating invalid/garbage session ids."""
        if not isinstance(session_id, str) or not session_id:
            return False
        # UUID (canonical) or UUID-with-suffix (for subagents): <uuid> or <uuid>.<suffix>
        root = session_id.split(".", 1)[0]
        try:
            uuid.UUID(root)
            return True
        except ValueError:
            return False

    def list_sessions(self, limit: int = 10) -> List[Dict[str, Any]]:
        """Return sessions for the UI.

        Shape matches existing /sessions protocol: id/title/directory/preview/created_at/updated_at.
        """
        sessions = self._persistent_mgr.list_sessions(limit=limit)
        session_list: List[Dict[str, Any]] = []

        for s in sessions[:limit]:
            preview = ""
            try:
                context_file = self._persistent_mgr.session_storage.storage_dir / s.id / "context.jsonl"
                if context_file.exists():
                    with open(context_file, "r", encoding="utf-8") as f:
                        first_line = f.readline().strip()
                        if first_line:
                            msg_data = json.loads(first_line)
                            if msg_data.get("role") == "user":
                                text = msg_data.get("content", "")
                                preview = text[:500] + ("..." if len(text) > 500 else "")
            except Exception as e:
                log_error(f"Failed to read preview for session {s.id}: {e}")

            session_list.append(
                {
                    "id": s.id,
                    "title": s.title,
                    "directory": s.directory,
                    "preview": preview,
                    "created_at": s.created_at.isoformat() if getattr(s, "created_at", None) else None,
                    "updated_at": s.updated_at.isoformat() if getattr(s, "updated_at", None) else None,
                }
            )

        return session_list
