import uuid
import requests
import logging

from odoo import models, fields, api

_logger = logging.getLogger(__name__)


class LogisticsRoute(models.Model):
    _name = 'logistics.route'
    _description = 'Logistics Route'
    _order = 'departure_node_id, arrival_node_id'

    uuid = fields.Char(
        string='UUID',
        required=True,
        readonly=True,
        default=lambda self: str(uuid.uuid4()),
        copy=False,
        help='Unique identifier for external systems'
    )

    name = fields.Char(
        string='Route Name',
        compute='_compute_name',
        store=True,
        help='Automatically generated route name'
    )
    
    departure_node_id = fields.Many2one(
        'logistics.node',
        string='Departure Node',
        required=True,
        help='Starting logistics node'
    )
    
    arrival_node_id = fields.Many2one(
        'logistics.node',
        string='Arrival Node',
        required=True,
        help='Destination logistics node'
    )
    
    transport_type = fields.Selection([
        ('auto', 'Automotive'),
        ('rail', 'Railway'),
        ('river', 'River'),
        ('sea', 'Maritime'),
        ('air', 'Air'),
        ('pipeline', 'Pipeline'),
    ], string='Transport Type', required=True)
    
    distance_km = fields.Float(
        string='Distance (km)',
        help='Route distance in kilometers'
    )
    
    travel_time_hours = fields.Float(
        string='Travel Time (hours)',
        required=True,
        help='Standard travel time in hours'
    )
    
    active = fields.Boolean(
        string='Active',
        default=True
    )

    @api.depends('departure_node_id', 'arrival_node_id', 'transport_type')
    def _compute_name(self):
        for record in self:
            if record.departure_node_id and record.arrival_node_id:
                departure = record.departure_node_id.name
                arrival = record.arrival_node_id.name
                transport = dict(record._fields['transport_type'].selection).get(record.transport_type, '')
                record.name = f"{departure} → {arrival} ({transport})"
            else:
                record.name = 'New Route'

    @api.constrains('departure_node_id', 'arrival_node_id')
    def _check_different_nodes(self):
        for record in self:
            if record.departure_node_id == record.arrival_node_id:
                raise ValueError("Departure and arrival nodes must be different")

    def name_get(self):
        result = []
        for record in self:
            result.append((record.id, record.name))
        return result

    def action_sync_to_maps(self):
        """Sync route to Optovia Maps via Kestra"""
        kestra_url = self.env['ir.config_parameter'].sudo().get_param('kestra.url', 'http://kestra:8080')
        try:
            response = requests.post(
                f"{kestra_url}/api/v1/executions/webhook/optovia.maps/sync-route/sync-route",
                json={"route_uuid": self.uuid},
                timeout=10
            )
            response.raise_for_status()
            _logger.info(f"Route {self.uuid} sync triggered successfully")
        except requests.RequestException as e:
            _logger.error(f"Failed to trigger route sync: {e}")
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': 'Optovia Maps',
                    'message': f'Failed to sync: {str(e)}',
                    'type': 'danger',
                }
            }

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': 'Optovia Maps',
                'message': 'Route sync started',
                'type': 'success',
            }
        }