from typing import Optional
from uuid import UUID

from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.orm import selectinload

from src.aeros_simulation.model import AerosSimulation
from src.aeros_simulation.service import (
    get_calc_result_by,
    get_default_simulation,
    get_simulation_by_id,
    get_simulation_node_by,
)
from src.auth.service import CurrentUser
from src.database.core import DbSession
from src.database.service import search_filter_sort_paginate
from tkinter.constants import E


async def get_model_data(*, db_session: DbSession, simulation_id: Optional[UUID]):
    if simulation_id:
        simulation = await get_simulation_by_id(db_session=db_session, simulation_id=simulation_id)
    else:
        simulation = await get_default_simulation(db_session=db_session)

    if not simulation:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="Simulation not found"
        )


    main_calc_data = await get_calc_result_by(
        db_session=db_session, simulation_id=simulation.id, node_name="- TJB - Unit 3 -"
    )


    # Total time period
    total_time = main_calc_data.total_uptime + main_calc_data.total_downtime

    # Availability Factor (same as your first formula - this one is correct)
    availability = (main_calc_data.availability) * 100

    # Equivalent Forced Outage Rate (EFOR)
    EFOR = main_calc_data.efor

    #Prediction
    EAF = main_calc_data.eaf
    Derating = main_calc_data.derating_hours
    Trip = main_calc_data.num_events
    EAF_KONKIN = main_calc_data.eaf_konkin
    
    
    #Realization
    EAF_REAL = 94
    EAF_KONKIN_REAL = 92

    powerplant_reliability = {
        "Plant Control": 98,
        "SPS": 98,
        "Turbine": 98,
        "Generator": 98,
        "Condensate Water": 98,
        "Feedwater System": 98,
        "Cooling Water": 98,
        "SCR": 98,
        "Ash Handling": 98,
        "Air Flue Gas": 98,
        "Boiler": 98,
        "SAC-IAC": 98,
        "KLH": 98,
        "CL": 98,
        "DESALINATION (CP)": 98,
        "FGD": 98,
        "CHS": 98,
        "SSB": 98,
        "WTP": 98,
    }

    return {
    "id": str(simulation.id), 
    "name": simulation.simulation_name,
    "availability": availability, 
    "EFOR": EFOR, 
     "EAF": {
        "Prediction_EAF": EAF,
        "Prediction_EAF_KONKIN": EAF_KONKIN,
        "Real_EAF": EAF_REAL,
        "Real_EAF_KONKIN": EAF_KONKIN_REAL
    },
     "Trip": {
         "Prediction_Trip": Trip,
         "Real_Trip": Trip
     },
     "Derating": {
         "Prediction_Derating": Derating,
         "Real_Derating": Derating
     },
    "powerplant_reliability": powerplant_reliability
}
