"""
Website management API endpoints
Handles deployment, download, and email functionality
"""

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse, StreamingResponse
from middleware.rate_limiter import rate_limit
from services.website_service import WebsiteService
from services.email_service import EmailService
from services.ai_service import AIService
import json
from pathlib import Path

router = APIRouter()

# Initialize services
website_service = WebsiteService()
email_service = EmailService()
ai_service = AIService()

@router.post("/generate-stream")
@rate_limit()  # Uses environment variables
async def generate_website_stream(request: Request):
    """
    Generate website with streaming response for live preview
    """
    try:
        # Get website data from request
        data = await request.json()
        
        # Create streaming response
        async def generate_stream():
            # Send initial status
            yield f"data: {json.dumps({'type': 'status', 'message': 'Starting website generation...'})}\n\n"
            
            # Delegate to service for business logic
            async for chunk_data in website_service.generate_website_stream(data):
                yield f"data: {json.dumps(chunk_data)}\n\n"
        
        # Use event-stream style chunking headers and disable proxy buffering
        # to reduce the chance of intermediate proxies buffering the response.
        return StreamingResponse(
            generate_stream(),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Type": "text/event-stream; charset=utf-8",
                # Nginx: disable buffering; some platforms respect this header
                "X-Accel-Buffering": "no",
            }
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Streaming generation failed: {str(e)}")

@router.get("/download/{folder_name}")
async def download_website(folder_name: str):
    """
    Download website as ZIP file
    """
    try:
        # Get website folder path
        website_path = Path("templates/generated") / folder_name
        
        if not website_path.exists():
            raise HTTPException(status_code=404, detail="Website not found")
        
        # Create ZIP file
        zip_path = await website_service.create_zip(website_path, folder_name)
        
        return FileResponse(
            path=zip_path,
            filename=f"{folder_name}.zip",
            media_type="application/zip",
            headers={
                "Content-Disposition": f"attachment; filename=\"{folder_name}.zip\"",
                "X-Content-Type-Options": "nosniff",
                "X-Frame-Options": "SAMEORIGIN",
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": "0"
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Download failed: {str(e)}")

@router.post("/send-zip")
async def send_zip_email(request: Request):
    """
    Send website ZIP via email
    """
    try:
        data = await request.json()

        # Build a dynamic host_url from the incoming request (no env variables)
        # Example: http://192.168.6.20:8000/
        host_url = str(request.base_url).rstrip('/')

        # Send email with ZIP attachment; pass host_url so email link is fully dynamic
        result = await email_service.send_website_email(
            email=data["email"],
            folder_name=data["folder_name"],
            website_name=data["website_name"],
            host_url=host_url,
        )
        
        return {"success": True, "message": "Email sent successfully"}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Email sending failed: {str(e)}")