from fastapi import APIRouter, Depends, HTTPException
from typing import List
from datetime import datetime
from psycopg import AsyncConnection

from app.infra.db.timescaledb.repositories.realtime import RealtimeRepository
from .dependencies import get_timescale_connection

router = APIRouter()


@router.post("/realtime/links/batch", status_code=201)
async def insert_realtime_links(
    data: List[dict], conn: AsyncConnection = Depends(get_timescale_connection)
):
    await RealtimeRepository.insert_links_batch(conn, data)
    return {"message": f"Inserted {len(data)} records"}


@router.get("/realtime/links")
async def get_realtime_links(
    start_time: datetime,
    end_time: datetime,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    return await RealtimeRepository.get_links_by_time_range(conn, start_time, end_time)


@router.delete("/realtime/links")
async def delete_realtime_links(
    start_time: datetime,
    end_time: datetime,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    await RealtimeRepository.delete_links_by_time_range(conn, start_time, end_time)
    return {"message": "Deleted successfully"}


@router.patch("/realtime/links/{link_id}/field")
async def update_realtime_link_field(
    link_id: str,
    time: datetime,
    field: str,
    value: float,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    try:
        await RealtimeRepository.update_link_field(conn, time, link_id, field, value)
        return {"message": "Updated successfully"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/realtime/nodes/batch", status_code=201)
async def insert_realtime_nodes(
    data: List[dict], conn: AsyncConnection = Depends(get_timescale_connection)
):
    await RealtimeRepository.insert_nodes_batch(conn, data)
    return {"message": f"Inserted {len(data)} records"}


@router.get("/realtime/nodes")
async def get_realtime_nodes(
    start_time: datetime,
    end_time: datetime,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    return await RealtimeRepository.get_nodes_by_time_range(conn, start_time, end_time)


@router.delete("/realtime/nodes")
async def delete_realtime_nodes(
    start_time: datetime,
    end_time: datetime,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    await RealtimeRepository.delete_nodes_by_time_range(conn, start_time, end_time)
    return {"message": "Deleted successfully"}


@router.post("/realtime/simulation/store", status_code=201)
async def store_realtime_simulation_result(
    node_result_list: List[dict],
    link_result_list: List[dict],
    result_start_time: str,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    """Store realtime simulation results to TimescaleDB"""
    await RealtimeRepository.store_realtime_simulation_result(
        conn, node_result_list, link_result_list, result_start_time
    )
    return {"message": "Simulation results stored successfully"}


@router.get("/realtime/query/by-time-property")
async def query_realtime_records_by_time_property(
    query_time: str,
    type: str,
    property: str,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    """Query all realtime records by time and property"""
    try:
        results = await RealtimeRepository.query_all_record_by_time_property(
            conn, query_time, type, property
        )
        return {"results": results}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/realtime/query/by-id-time")
async def query_realtime_simulation_by_id_time(
    id: str,
    type: str,
    query_time: str,
    conn: AsyncConnection = Depends(get_timescale_connection),
):
    """Query realtime simulation results by id and time"""
    try:
        results = await RealtimeRepository.query_simulation_result_by_id_time(
            conn, id, type, query_time
        )
        return {"result": results}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
