from fastapi import APIRouter, Request, Form
from fastapi.templating import Jinja2Templates
from models.models import MODELS, runner
from datasets.datasets import DATASETS
from models.utils import save_result, load_results, predict_yolo
from datasets.MC_NDCC import MC_NDCC
import glob
import os
import time


router = APIRouter(prefix="/projects", tags=["projects"])
templates = Jinja2Templates(directory="templates")

@router.get("")
async def get_projects(request: Request):
    return templates.TemplateResponse("projects.html", {"request": request, "title": "Projects"})

@router.get("/run-models")
async def run_models(request: Request):
    results = load_results(limit = 20, results_file='templates/static/public/files/results.csv')

    return templates.TemplateResponse("projects/run_models.html", {"request": request, "title": "Run Models", "models": MODELS, "datasets": DATASETS, "results": results})

@router.post("/run-models")
async def run_models(request: Request,
    model: str = Form(...),
    dataset: str = Form(...),
    C1: float = Form(None),
    C2: float = Form(None),
    C3: float = Form(None),
    C4: float = Form(None),
    C5: float = Form(None),
    C6: float = Form(None),

    ):

    params = None

    if model == MODELS[0]:
        params = {'C': C1}
    elif model == MODELS[1]:
        params = {'C': C1}
    elif model == MODELS[2]:
        params = {'C': [C1, C2, C3, C4, C5, C6]}
    elif model == MODELS[3]:
        params = {'C': [C1, C2]}
    elif model == MODELS[4]:
        params = {'C': [C1, C2]}
    


    result = runner(model, dataset, params)

    save_result(result['model'], result['dataset'], result['accuracy'], result['params'], results_file='templates/static/public/files/results.csv')
    
    results = load_results(limit = 20, results_file='templates/static/public/files/results.csv')



    return templates.TemplateResponse("projects/run_models.html", 
                                      {"request": request, 
                                       "title": "Run Models", 
                                       "models": MODELS, 
                                       "datasets": DATASETS,
                                       "selected_model": model,
                                       "selected_dataset": dataset,
                                       "results": results
                                       })



@router.get("/generate-ndcc")
async def generate_ndcc(request: Request):

    return templates.TemplateResponse("projects/generate_ndcc.html", 
                                      {"request": request,
                                        "centers": 1,
                                        "nos": 100,
                                        "nof": 10,
                                        "noc": 2,
                                       "title": "Generate NDCC Dataset"
                                       })


@router.post("/generate-ndcc")
async def generate_ndcc(request: Request,
    centers: int = Form(None),
    nos: int = Form(None),
    nof: int = Form(None),
    noc: int = Form(None)
):
    
    tmp_dir = "templates/static/public/files"

    for f in glob.glob(os.path.join(tmp_dir, "NDCC_*.csv")):
        try:
            os.remove(f)
        except Exception as e:
            print(f"Could not remove {f}: {e}")
    
    ndccObj = MC_NDCC(centers, nos, nof, noc)


    
    dataset_name = f"NDCC_{nos}_{nof}_{noc}.csv"
    _ = ndccObj.get_csv(f"templates/static/public/files/NDCC_{nos}_{nof}_{noc}.csv")

    print(dataset_name)
    
    return templates.TemplateResponse("projects/generate_ndcc.html", 
                                    {"request": request, 
                                    "title": "Generate NDCC Dataset", 
                                    "centers": centers,
                                    "nos": nos,
                                    "nof": nof,
                                    "noc": noc,
                                    "dataset_name": dataset_name,
                                    })



@router.get("/run-yolo")
async def run_yolo(request: Request,
):

    images = [
        "RPf_00152.png",
        "RPf_00153.png",
        "RPf_00156.png",
        "RPf_00200.png",
        "RPf_00201.png",
        "RPf_00202.png",
        "RPf_00281.png",
        "RPf_00282.png",
        "RPf_00283.png",
        "RPf_00291.png",
        "RPf_00293.png",
        "RPf_00294.png",
        "RPf_00302.png",
        "RPf_00303.png",
        "RPf_00304.png",
        "RPf_00310.png",
        "RPf_00311.png",
        "RPf_00312.png",
    ]

    return templates.TemplateResponse("projects/run_yolo.html", {
        "request": request,
        "title": "Run Yolo",
        "images": images,
        "selected_image": images[0]

    })


@router.post("/run-yolo")
async def run_yolo_post(
    request: Request,
    selected_image: str = Form(...),
    confidence: float = Form(...)
):
    images = [
        "RPf_00152.png",
        "RPf_00153.png",
        "RPf_00156.png",
        "RPf_00200.png",
        "RPf_00201.png",
        "RPf_00202.png",
        "RPf_00281.png",
        "RPf_00282.png",
        "RPf_00283.png",
        "RPf_00291.png",
        "RPf_00293.png",
        "RPf_00294.png",
        "RPf_00302.png",
        "RPf_00303.png",
        "RPf_00304.png",
        "RPf_00310.png",
        "RPf_00311.png",
        "RPf_00312.png",
    ]

    # Run YOLO prediction
    file_path = "templates/static/public/files/repair/predicted/predicted_image.jpg"

    if os.path.exists(file_path):
        os.remove(file_path)
        print("File removed.")
    else:
        print("File does not exist.")

    _ = predict_yolo(selected_image, confidence)

    # Add cache-busting query string (timestamp)
    result_url = f"../static/public/files/repair/predicted/predicted_image.jpg?{int(time.time())}"

    return templates.TemplateResponse("projects/run_yolo.html", {
        "request": request,
        "title": "Run Yolo",
        "images": images,
        "selected_image": selected_image,
        "selected_confidence": confidence,
        "result_path": result_url
    })