import uuid
import requests
import logging

from odoo import models, fields, api

_logger = logging.getLogger(__name__)


class LogisticsSchedule(models.Model):
    _name = 'logistics.schedule'
    _description = 'Logistics Schedule'
    _order = 'departure_node_id, arrival_node_id, departure_time'

    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='Schedule Name',
        compute='_compute_name',
        store=True,
        help='Automatically generated schedule 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'
    )
    
    route_id = fields.Many2one(
        'logistics.route',
        string='Route',
        required=True,
        help='Route for this schedule'
    )
    
    departure_time = fields.Float(
        string='Departure Time',
        help='Departure time in hours (0-24 format, e.g., 14.5 for 14:30)'
    )
    
    frequency = fields.Selection([
        ('daily', 'Daily'),
        ('weekly', 'Weekly'),
        ('biweekly', 'Bi-weekly'),
        ('monthly', 'Monthly'),
        ('seasonal', 'Seasonal'),
        ('on_demand', 'On Demand'),
    ], string='Frequency', required=True, default='weekly')
    
    active = fields.Boolean(
        string='Active',
        default=True
    )

    @api.depends('departure_node_id', 'arrival_node_id', 'departure_time', 'frequency')
    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
                frequency = dict(record._fields['frequency'].selection).get(record.frequency, '')
                time_str = ''
                if record.departure_time:
                    hours = int(record.departure_time)
                    minutes = int((record.departure_time - hours) * 60)
                    time_str = f" {hours:02d}:{minutes:02d}"
                record.name = f"{departure} → {arrival} ({frequency}{time_str})"
            else:
                record.name = 'New Schedule'

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

    def action_sync_to_maps(self):
        """Sync schedule 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-schedule/sync-schedule",
                json={"schedule_uuid": self.uuid},
                timeout=10
            )
            response.raise_for_status()
            _logger.info(f"Schedule {self.uuid} sync triggered successfully")
        except requests.RequestException as e:
            _logger.error(f"Failed to trigger schedule 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': 'Schedule sync started',
                'type': 'success',
            }
        }