from odoo import models, fields, api
import json
import logging
import requests
import uuid

_logger = logging.getLogger(__name__)


class LogisticsNode(models.Model):
    _name = 'logistics.node'
    _description = 'Logistics Node'
    _order = 'name'

    uuid = fields.Char(
        string='UUID',
        required=True,
        readonly=True,
        default=lambda self: str(uuid.uuid4()),
        help='Unique identifier for this node across all systems'
    )
    
    name = fields.Char(
        string='Node Name',
        required=True,
        help='Name of the logistics node'
    )
    
    latitude = fields.Float(
        string='Latitude',
        required=True,
        digits=(10, 7),
        help='Latitude coordinates in decimal degrees'
    )
    
    longitude = fields.Float(
        string='Longitude', 
        required=True,
        digits=(10, 7),
        help='Longitude coordinates in decimal degrees'
    )
    
    country_id = fields.Many2one('res.country', string='Country', required=True)
    
    
    
    connection_ids = fields.One2many(
        'logistics.node.connection',
        'node_id',
        string='Connections',
        help='Available connection types for this node'
    )
    
    isochrone_ids = fields.One2many(
        'logistics.isochrone',
        'node_id',
        string='Isochrones',
        help='Generated isochrones for different durations'
    )
    
    @api.depends('connection_ids.transport_category_id')
    def _compute_has_auto_connection(self):
        for record in self:
            record.has_auto_connection = any(
                conn.transport_category_id.code == 'auto' and conn.active 
                for conn in record.connection_ids if conn.transport_category_id
            )
    
    has_auto_connection = fields.Boolean(
        string='Has Auto Connection',
        compute='_compute_has_auto_connection',
        store=True
    )
    

    @api.model
    def create(self, vals):
        node = super().create(vals)
        return node
    
    def write(self, vals):
        result = super().write(vals)
        return result
    
    def _trigger_graph_creation(self, graph_method="geodesic", duration_minutes=1200):
        """Добавляет ноду в граф выбранным методом"""
        import os
        # Настройка подключения к Prefect ПЕРЕД импортом
        os.environ['PREFECT_API_URL'] = 'http://prefect_server:4200/api'
        
        import asyncio
        from prefect import get_client
        
        async def create_flow_run():
            
            async with get_client() as client:
                # Получаем deployment по имени
                deployment = await client.read_deployment_by_name("add-node-to-graph/graph-deployment")
                
                # Создаем flow run
                flow_run = await client.create_flow_run_from_deployment(
                    deployment.id,
                    parameters={
                        "node_uuid": self.uuid,
                        "country": self.country_id.code,
                        "latitude": self.latitude,
                        "longitude": self.longitude,
                        "connection_types": [conn.connection_type for conn in self.connection_ids if conn.active],
                        "odoo_url": "http://odoo_local:8069",
                        "graph_method": graph_method,
                        "duration_minutes": duration_minutes
                    }
                )
                return flow_run
        
        # Запускаем async функцию
        asyncio.run(create_flow_run())
    
    def action_add_to_graph(self):
        """Open dialog to add node to graph with method selection"""
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'logistics.graph.wizard',
            'view_mode': 'form',
            'target': 'new',
            'context': {'default_node_id': self.id, 'default_node_uuid': self.uuid, 'default_country': self.country_id.code}
        }
    
    
