"""
Export routes — PPTX and DOCX with permission checks.
"""

import re
from pydantic import BaseModel
from typing import Optional

from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
import io

from backend.database import get_db
from backend.auth import get_current_user, check_feature
from backend.models import User
from backend.services.pptx_service import generate_pptx
from backend.services.docx_service import generate_docx
from sqlalchemy.orm import Session

router = APIRouter()


class ExportBody(BaseModel):
    markdown: str
    title: Optional[str] = None


def _safe_filename(title: str, ext: str) -> str:
    if not title or title == "New Chat":
        return f"document.{ext}"
    safe = re.sub(r'[^\w\s-]', '', title).strip()
    safe = re.sub(r'\s+', '-', safe)[:60] or "document"
    return f"{safe}.{ext}"


@router.post("/pptx")
def export_pptx(body: ExportBody, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    check_feature(user.id, "export_pptx", db)
    title = body.title or "Presentation"
    data = generate_pptx(body.markdown, title)
    filename = _safe_filename(title, "pptx")
    return StreamingResponse(
        io.BytesIO(data),
        media_type="application/vnd.openxmlformats-officedocument.presentationml.presentation",
        headers={"Content-Disposition": f'attachment; filename="{filename}"'},
    )


@router.post("/docx")
def export_docx(body: ExportBody, user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    check_feature(user.id, "export_docx", db)
    title = body.title or "Document"
    data = generate_docx(body.markdown, title)
    filename = _safe_filename(title, "docx")
    return StreamingResponse(
        io.BytesIO(data),
        media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        headers={"Content-Disposition": f'attachment; filename="{filename}"'},
    )