import os
from typing import List, Optional

from fastapi import APIRouter, HTTPException, Response, status, File, UploadFile, Form
from fastapi.responses import StreamingResponse
import httpx
from sqlalchemy import select

from src.aeros_project.model import AerosProject
from src.auth.service import CurrentUser
from src.config import WINDOWS_AEROS_BASE_URL
from src.database.core import DbSession
from src.database.service import CommonParameters
from src.models import StandardResponse
from src.aeros_utils import aeros_post
from .schema import AerosProjectInput, AerosMetadata, OverhaulScheduleCreate, OverhaulScheduleUpdate
from .service import import_aro_project, fetch_aro_record, reset_project, create, update, delete

router = APIRouter()

@router.post("", response_model=StandardResponse[str])
async def import_aro(
    db_session: DbSession,
    current_user: CurrentUser,
    schematic_name: str = Form(...),
    aro_file: UploadFile = File(..., description="ARO file"),
    project_name: str = "trialapi"
):

    if current_user.role.lower() != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Admin access required to modify Aeros files."
        )

    # Create the input object manually
    aeros_project_input = AerosProjectInput(schematic_name=schematic_name, aro_file=aro_file)

    result = await import_aro_project(db_session=db_session, aeros_project_in=aeros_project_input)

    return {"data": result, "status": "success", "message": "Success"}


@router.get("/download")
async def forward_download(db_session: DbSession):
    query = select(AerosProject)
    data = await db_session.execute(query)
    
    project = data.scalar_one_or_none()
    filename = f"{project.project_name}.aro"

    try:
        # Download entire file (no streaming)
        response = await aeros_post(
                "/download",
                json={
                    "filename": filename
                },
        )

        if response.status_code != 200:
            raise HTTPException(
                status_code=response.status_code,
                detail="Failed to download from upstream service"
            )

        file_bytes = response.content  # full file in memory

        # Extract headers
        # Force a secure/default filename for the client
        content_disposition = f'attachment; filename="{filename}"'
        media_type = response.headers.get(
            "content-type",
            "application/octet-stream"
        )

        # Return as ordinary file response
        return Response(
            content=file_bytes,
            media_type=media_type,
            headers={"Content-Disposition": content_disposition}
        )

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


@router.get("/metadata", response_model=StandardResponse[AerosMetadata])
async def getAerosMetadata(db_session: DbSession):
    result = await fetch_aro_record(db_session=db_session)

    return {"data": result, "status": "success", "message": "Success"}


@router.get("/reset", response_model=StandardResponse[str])
async def reset_aeros_project(db_session: DbSession):
    # Logic to reset the ARO project
    reset_path = await reset_project(db_session=db_session)

    return {
        "data": reset_path,
        "message": "Success"
    }

# @router.post("", response_model=StandardResponse[None])
# async def import_aro_old(db_session: DbSession, aeros_project_in: AerosProjectInput, project_name: str = "trialapi"):
#     # TEST ONLY
#     # return {'file': 'ok'}

#     await import_aro_project(db_session=db_session, aeros_project_in=aeros_project_in)

#     return {"data": None, "status": "success", "message": "Success"}


# @router.post("/import")
# async def upload_with_validation(aeros_project_in: AerosProjectInput):
#     # Check file extension


#     return {
#         "message": "File uploaded successfully",
#         "filename": file.filename,
#         "size": len(content)
#     }


@router.post("/overhaul_job", response_model=StandardResponse[None])
async def create_overhaul_equipment_jobs(
    db_session: DbSession, overhaul_job_in: OverhaulScheduleCreate
):
    await create(
        db_session=db_session,
        overhaul_job_in=overhaul_job_in,
    )

    return StandardResponse(
        data=None,
        message="Data created successfully",
    )

@router.post("/update/{overhaul_job_id}", response_model=StandardResponse[None])
async def update_overhaul_schedule(
    db_session: DbSession, overhaul_job_id: str, overhaul_job_in: OverhaulScheduleUpdate
):
    await update(db_session=db_session, overhaul_schedule_id=overhaul_job_id, overhaul_job_in=overhaul_job_in)

    return StandardResponse(
        data=None,
        message="Data updated successfully",
    )

@router.post("/delete/{overhaul_job_id}", response_model=StandardResponse[None])
async def delete_overhaul_equipment_job(db_session: DbSession, overhaul_job_id: str):
    await delete(db_session=db_session, overhaul_schedule_id=overhaul_job_id)

    return StandardResponse(
        data=None,
        message="Data deleted successfully",
    )
