from fastapi import APIRouter, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse
from pydantic import BaseModel
from app.services.geom_service import create_geometry
from app.services.hash_generator import generate_hash
from app.services.minio_service import check_file_exists_minio, upload_to_minio, get_file_from_minio
from app.db.utils import save_params_to_db
from app.core.constants import MINIO_BUCKET_NAME, DEFAULT_VALUES
from app.core.config import settings
from .utils import remove_file

import os

router = APIRouter()


class GeomParams(BaseModel):
    N1: float = DEFAULT_VALUES["N1"]
    L1: float = DEFAULT_VALUES["L1"]
    a1: float = DEFAULT_VALUES["a1"]
    N2: float = DEFAULT_VALUES["N2"]
    L2: float = DEFAULT_VALUES["L2"]
    N3: float = DEFAULT_VALUES["N3"]
    L3: float = DEFAULT_VALUES["L3"]


async def generate_geom(params: GeomParams):
    params_dict = params.model_dump()
    file_id = generate_hash(params_dict)
    file_name = file_id + ".stp"

    if check_file_exists_minio(MINIO_BUCKET_NAME, file_name):
        print(f"Файл {file_name} уже существует в MinIO. Возвращаем его.")
        temp_path = os.path.join(settings.current_directory, "tmp/")
        if not os.path.exists(temp_path):
            os.makedirs(temp_path)
        temp_file_path = os.path.join(temp_path, file_name)
        get_file_from_minio(MINIO_BUCKET_NAME, file_name, temp_file_path)
        return temp_file_path

    file_path = create_geometry(params_dict, file_name)
    upload_to_minio(MINIO_BUCKET_NAME, file_path, file_name)
    save_params_to_db(params_dict, file_name)

    return file_path


@router.post("/generate_geom")
async def generate_geom_endpoint(params: GeomParams, background_tasks: BackgroundTasks):
    file_path = await generate_geom(params)
    background_tasks.add_task(remove_file, file_path)
    return FileResponse(file_path, media_type='application/octet-stream', filename=os.path.basename(file_path))


@router.get("/check_geom/{file_name}")
async def check_geom(file_name: str):
    if check_file_exists_minio(MINIO_BUCKET_NAME, file_name):
        return {"status": "exists"}
    return {"status": "not found"}


@router.post("/get_file_name")
async def check_geom(params: GeomParams):
    params_dict = params.model_dump()
    file_id = generate_hash(params_dict)
    file_name = file_id + ".stp"
    return {"file_name": file_name}
