# main.py

from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from typing import List
from pydantic import BaseModel, model_validator
import uvicorn

from Temp_Diag import MSET_Temp  

app = FastAPI(title="Temperature Diagnosis API")


class TemperatureInput(BaseModel):
    windCode: str
    windTurbineNumberList: List[str]
    startTime: str  # e.g. "2024-06-08 00:00"
    endTime: str    # e.g. "2024-06-08 01:00"

    @model_validator(mode='before')
    def normalize_fields(cls, values):
        # 确保 windTurbineNumberList 是列表
        raw = values.get('windTurbineNumberList')
        if isinstance(raw, str):
            values['windTurbineNumberList'] = [raw]
        return values

# 阈值分析
@app.post("/temperature/threshold")
async def route_threshold(input_data: TemperatureInput):
    """
    阈值分析接口（阈值固定 0.99）：
      - 输入：
        {
          "windCode": "WOF01000010",
          "windTurbineNumberList": ["WOG00542"],
          "startTime": "2023-01-01 00:00",
          "endTime": "2023-01-05 12:00"
        }
      - 返回：
        {
          "data": {
            "type": "temperature_threshold",
            "records": [
              {
                "time_stamp": "2024-06-08 00:05:00",
                "temp_channel": "main_bearing_temperature",
                "SPRT_score": 0.123,
                "status": "正常"
              },
              ...
            ]
          },
          "code": 200,
          "message": "success"
        }
    """
    try:
        analyzer = MSET_Temp(
            windCode=input_data.windCode,
            windTurbineNumberList=input_data.windTurbineNumberList,
            startTime=input_data.startTime,
            endTime=input_data.endTime
        )
        df_result = analyzer.check_threshold()  # DataFrame 长格式
        records = df_result.to_dict(orient="records")
        return {
            "data": {
                "type": "temperature_threshold",
                "records": records
            },
            "code": 200,
            "message": "success"
        }
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "code": 500,
                "message": "analysis failed",
                "detail": str(e)
            }
        )

# 趋势分析（暂未调用）
@app.post("/temperature/trend")
async def route_trend(input_data: TemperatureInput):
    """
    趋势分析接口：
      - 输入：
        {
          "windCode": "WOF01000010",
          "windTurbineNumberList": ["WOG00542"],
          "startTime": "2023-01-01 00:00",
          "endTime": "2023-01-05 12:00"
        }
      - 返回：
        {
          "data": {
            "type": "temperature_trend",
            "timestamps": [ "2024-06-08 00:00:00", ... ],
            "channels": [
               { "temp_channel": "main_bearing_temperature", "values": [24.5, 24.7, ...] },
               ...
            ],
            "unit": "°C"
          },
          "code": 200,
          "message": "success"
        }
    """
    try:
        analyzer = MSET_Temp(
            windCode=input_data.windCode,
            windTurbineNumberList=input_data.windTurbineNumberList,
            startTime=input_data.startTime,
            endTime=input_data.endTime
        )
        result = analyzer.get_trend()
        return {
            "data": {
                "type": "temperature_trend",
                **result
            },
            "code": 200,
            "message": "success"
        }
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={
                "code": 500,
                "message": "analysis failed",
                "detail": str(e)
            }
        )



if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )
