from fastapi import FastAPI, UploadFile, File, Form
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import Request
import os
from services.ffmpeg_service import process_video

# Get absolute paths
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
PROCESSED_DIR = os.path.join(BASE_DIR, "processed_videos")  # Changed from RESULTS_DIR

app = FastAPI()

# Mount static and processed_videos directories with absolute paths
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/processed", StaticFiles(directory=PROCESSED_DIR), name="processed")  # Changed from /results
templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/process")
async def upload_video(
    request: Request,
    country: str = Form(...),
    channel: str = Form(...),
    file: UploadFile = File(..., alias="video_file")  # Note the alias to match the form field name
):
    output_file_path = await process_video(country, channel, file)
    return templates.TemplateResponse("index.html", {
        "request": request, 
        "download_link": output_file_path
    })