from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import List
from odoo import http
from odoo.addons.fastapi.dependencies import odoo_env

router = APIRouter(tags=["logistics"])


class IsochroneCreateRequest(BaseModel):
    node_uuid: str
    duration_minutes: int
    uuid: str


class LogisticsNodeResponse(BaseModel):
    uuid: str
    name: str
    latitude: float
    longitude: float
    country: str


@router.get("/nodes")
def get_logistics_nodes(env=Depends(odoo_env)) -> List[LogisticsNodeResponse]:
    """Получить список всех логистических узлов"""
    
    LogisticsNode = env['logistics.node']
    nodes = LogisticsNode.search([])
    
    result = []
    for node in nodes:
        result.append(LogisticsNodeResponse(
            uuid=node.uuid,
            name=node.name,
            latitude=node.latitude,
            longitude=node.longitude,
            country=node.country_id.name if node.country_id else ''
        ))
    
    return result


@router.get("/nodes/{node_uuid}")
def get_logistics_node(node_uuid: str, env=Depends(odoo_env)) -> LogisticsNodeResponse:
    """Получить логистический узел по UUID"""
    
    LogisticsNode = env['logistics.node']
    node = LogisticsNode.search([('uuid', '=', node_uuid)], limit=1)
    
    if not node:
        raise HTTPException(status_code=404, detail=f"Node with UUID {node_uuid} not found")
    
    return LogisticsNodeResponse(
        uuid=node.uuid,
        name=node.name,
        latitude=node.latitude,
        longitude=node.longitude,
        country=node.country_id.name if node.country_id else ''
    )


@router.post("/isochrones/create")
def create_isochrone_record(
    isochrone_data: IsochroneCreateRequest,
    env=Depends(odoo_env)
):
    """Creates isochrone record from Prefect flow"""
    
    LogisticsIsochrone = env['logistics.isochrone']
    
    # Найдем ноду по UUID
    LogisticsNode = env['logistics.node']
    node = LogisticsNode.search([('uuid', '=', isochrone_data.node_uuid)], limit=1)
    
    if not node:
        raise HTTPException(status_code=404, detail=f"Node with UUID {isochrone_data.node_uuid} not found")
    
    isochrone_vals = {
        'node_id': node.id,
        'duration_minutes': isochrone_data.duration_minutes,
        'uuid': isochrone_data.uuid,
    }
    
    isochrone = LogisticsIsochrone.create(isochrone_vals)
    env.cr.commit()
    
    return {
        "success": True,
        "isochrone_id": isochrone.id,
        "uuid": isochrone_data.uuid,
        "node_id": node.id,
        "duration_minutes": isochrone_data.duration_minutes,
        "message": "Isochrone record created successfully"
    }