"""
replay.py
---------
API endpoints for memory replay and export (Phase 4).
"""
from datetime import datetime
from typing import Optional, Literal
import json
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from hieromem_core.memory import Memory
from hieromem_api.deps import get_memory_engine
from hieromem_api.auth import require_permission
from hieromem_api.rbac import Permission

router = APIRouter(prefix="/replay", tags=["Replay"])


@router.get("/export")
def export_memory(
    namespace: Optional[str] = None,
    format: Literal["jsonl", "list"] = "jsonl",
    start: Optional[datetime] = None,
    end: Optional[datetime] = None,
    memory: Memory = Depends(get_memory_engine),
    _perm: None = Depends(require_permission(Permission.READ_MEMORY))
):
    """Export memory episodes as training data."""
    try:
        data = memory.export_training_data(
            namespace=namespace,
            format=format,
            include_graph=True,
            start=start,
            end=end
        )

        if format == "jsonl":
            # Return as downloadable file
            return StreamingResponse(
                iter([data]),
                media_type="application/x-jsonlines",
                headers={
                    "Content-Disposition": f"attachment; filename=memory_export_{datetime.now().isoformat()}.jsonl"
                }
            )
        else:
            return data

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/stream")
async def stream_replay(
    namespace: Optional[str] = None,
    start: Optional[datetime] = None,
    end: Optional[datetime] = None,
    memory: Memory = Depends(get_memory_engine),
    _perm: None = Depends(require_permission(Permission.READ_MEMORY))
):
    """Stream episodes in chronological order (Server-Sent Events)."""

    def event_generator():
        for ep in memory.replay(start=start, end=end, namespace=namespace):
            # Format episode compact for stream
            data = {
                "id": ep.id,
                "timestamp": ep.tocc.isoformat(),
                "content": ep.meta.get("text", "") if ep.meta else "",
                "trust": ep.trust
            }
            yield f"data: {json.dumps(data)}\n\n"
        yield "event: done\ndata: {}\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream"
    )
