import logging

from odoo import models, fields

_logger = logging.getLogger(__name__)


class StockPicking(models.Model):
    _inherit = 'stock.picking'

    woo_tracking_number = fields.Char(string='WC Tracking Number')
    woo_carrier_id = fields.Many2one('woo.shipping.carrier', string='WC Shipping Carrier')
    woo_shipment_ids = fields.One2many('woo.shipment', 'picking_id', string='WC Shipments')
    is_woo_delivery = fields.Boolean(compute='_compute_is_woo_delivery', string='Is WC Delivery')

    def _compute_is_woo_delivery(self):
        for picking in self:
            picking.is_woo_delivery = bool(picking.woo_shipment_ids) or bool(
                picking.sale_id and picking.sale_id.woo_bind_ids
            )

    def button_validate(self):
        """Override to auto-create shipment and push tracking to WC."""
        res = super().button_validate()
        for picking in self:
            if not picking.sale_id or not picking.sale_id.woo_bind_ids:
                continue
            woo_order = picking.sale_id.woo_bind_ids[0]
            # Create shipment record
            shipment_vals = {
                'order_id': woo_order.id,
                'picking_id': picking.id,
                'carrier_id': picking.woo_carrier_id.id if picking.woo_carrier_id else False,
                'tracking_number': picking.woo_tracking_number or '',
                'shipped_date': fields.Datetime.now(),
                'is_backorder': bool(picking.backorder_ids),
                'company_id': picking.company_id.id,
            }
            shipment = self.env['woo.shipment'].create(shipment_vals)

            # Auto-push to WC if tracking number is set
            if picking.woo_tracking_number:
                try:
                    woo_order.action_push_shipping(
                        picking.woo_tracking_number,
                        picking.woo_carrier_id.id if picking.woo_carrier_id else False,
                    )
                    shipment.synced_to_woo = True
                except Exception as e:
                    _logger.error("Failed to push shipping to WC: %s", e)

            # Push delivery PDF
            try:
                woo_order.action_push_delivery_pdf(picking)
            except Exception as e:
                _logger.warning("Failed to push delivery PDF to WC: %s", e)
        return res
