"""
Session management for Video Viewer Bot.
Stores user context for conversation continuity.
"""

import json
import os
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Optional

NFS_BASE = os.getenv("NFS_BASE", "/mnt/video")
SESSIONS_DIR = Path(NFS_BASE) / "_viewer" / "sessions"

MAX_SEARCH_HISTORY = 10
MAX_VIEWED_VIDEOS = 20
MAX_CONVERSATION_CONTEXT = 5


@dataclass
class UserSession:
    user_id: int
    recent_searches: list = field(default_factory=list)  # [{query, results, timestamp}]
    viewed_videos: list = field(default_factory=list)  # [task_id, ...]
    last_video: Optional[str] = None  # Last viewed task_id
    last_product: Optional[str] = None  # Last viewed product_id
    conversation_context: list = field(default_factory=list)  # [{role, content}]
    created_at: Optional[str] = None
    updated_at: Optional[str] = None


def _session_path(user_id: int) -> Path:
    return SESSIONS_DIR / f"user_{user_id}.json"


def load_session(user_id: int) -> UserSession:
    """Load user session or create new one."""
    path = _session_path(user_id)

    if path.exists():
        try:
            data = json.loads(path.read_text())
            return UserSession(
                user_id=data.get("user_id", user_id),
                recent_searches=data.get("recent_searches", []),
                viewed_videos=data.get("viewed_videos", []),
                last_video=data.get("last_video"),
                last_product=data.get("last_product"),
                conversation_context=data.get("conversation_context", []),
                created_at=data.get("created_at"),
                updated_at=data.get("updated_at")
            )
        except (json.JSONDecodeError, ValueError):
            pass

    # New session
    return UserSession(
        user_id=user_id,
        created_at=datetime.now().isoformat()
    )


def save_session(session: UserSession):
    """Save user session to disk."""
    SESSIONS_DIR.mkdir(parents=True, exist_ok=True)

    session.updated_at = datetime.now().isoformat()

    # Trim lists to prevent unbounded growth
    session.recent_searches = session.recent_searches[-MAX_SEARCH_HISTORY:]
    session.viewed_videos = session.viewed_videos[-MAX_VIEWED_VIDEOS:]
    session.conversation_context = session.conversation_context[-MAX_CONVERSATION_CONTEXT:]

    path = _session_path(session.user_id)
    path.write_text(json.dumps(asdict(session), ensure_ascii=False, indent=2))


def add_search(session: UserSession, query: str, results: list):
    """Add search to history."""
    session.recent_searches.append({
        "query": query,
        "results": results[:5],  # Store up to 5 result task_ids
        "timestamp": datetime.now().isoformat()
    })
    save_session(session)


def add_viewed_video(session: UserSession, task_id: str):
    """Track viewed video."""
    # Remove if already in list (avoid duplicates)
    if task_id in session.viewed_videos:
        session.viewed_videos.remove(task_id)
    session.viewed_videos.append(task_id)
    session.last_video = task_id
    save_session(session)


def set_last_product(session: UserSession, product_id: str):
    """Track last viewed product."""
    session.last_product = product_id
    save_session(session)


def add_to_context(session: UserSession, role: str, content: str):
    """Add message to conversation context."""
    session.conversation_context.append({
        "role": role,
        "content": content,
        "timestamp": datetime.now().isoformat()
    })
    save_session(session)


def clear_context(session: UserSession):
    """Clear conversation context."""
    session.conversation_context = []
    save_session(session)


def get_context_summary(session: UserSession) -> str:
    """Get formatted context for Claude prompts."""
    parts = []

    if session.last_video:
        parts.append(f"Last viewed video: {session.last_video}")

    if session.last_product:
        parts.append(f"Last viewed product: {session.last_product}")

    if session.recent_searches:
        recent = session.recent_searches[-3:]
        queries = [s["query"] for s in recent]
        parts.append(f"Recent searches: {', '.join(queries)}")

    if session.conversation_context:
        recent_ctx = session.conversation_context[-3:]
        for ctx in recent_ctx:
            parts.append(f"[{ctx['role']}]: {ctx['content'][:100]}")

    return "\n".join(parts) if parts else "No prior context"
