"""
Preview API endpoints
Handles real-time preview functionality
"""

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, FileResponse
from pathlib import Path

router = APIRouter()

@router.get("/preview/{folder_name}")
async def get_preview(folder_name: str):
    """
    Get website preview
    """
    try:
        # Get website folder path
        website_path = Path("templates/generated") / folder_name
        index_file = website_path / "index.html"
        
        if not index_file.exists():
            raise HTTPException(status_code=404, detail="Website not found")
        
        # Read HTML content
        html_content = index_file.read_text(encoding="utf-8")
        
        return HTMLResponse(content=html_content)
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Preview failed: {str(e)}")

@router.get("/preview/asset/{file_path:path}")
async def get_preview_asset(request: Request, file_path: str):
    """
    Get static assets from generated website folder
    Determines folder name from referrer header or uses most recent folder
    """
    try:
        # Try to get folder name from referrer header
        referrer = request.headers.get("referer", "")
        folder_name = None
        
        if referrer and "/api/preview/" in referrer:
            # Extract folder name from referrer URL
            # e.g., http://localhost:8000/api/preview/dummy_diner_2025_09_09_18_55_45
            parts = referrer.split("/api/preview/")
            if len(parts) > 1:
                folder_name = parts[1].split("/")[0].split("?")[0]
        
        # If no folder name from referrer, find the most recent folder
        if not folder_name:
            generated_path = Path("templates/generated")
            if not generated_path.exists():
                raise HTTPException(status_code=404, detail="No generated websites found")
            
            folders = [f for f in generated_path.iterdir() if f.is_dir()]
            if not folders:
                raise HTTPException(status_code=404, detail="No generated websites found")
            
            # Sort by modification time, newest first
            latest_folder = max(folders, key=lambda f: f.stat().st_mtime)
            folder_name = latest_folder.name
        
        # Get website folder path
        website_path = Path("templates/generated") / folder_name
        asset_file = website_path / "asset" / file_path
        
        if not asset_file.exists() or not asset_file.is_file():
            raise HTTPException(status_code=404, detail="Asset not found")
        
        # Determine media type based on file extension
        media_type = "application/octet-stream"
        if file_path.endswith('.svg'):
            media_type = "image/svg+xml"
        elif file_path.endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp')):
            media_type = "image/" + file_path.split('.')[-1]
        elif file_path.endswith('.css'):
            media_type = "text/css"
        elif file_path.endswith('.js'):
            media_type = "application/javascript"
        
        return FileResponse(
            path=str(asset_file),
            media_type=media_type
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Asset loading failed: {str(e)}")