import logging

from odoo import api, fields, models

_logger = logging.getLogger(__name__)


class WooCustomer(models.Model):
    _name = 'woo.customer'
    _description = 'WooCommerce Customer'

    instance_id = fields.Many2one('woo.instance', required=True, ondelete='cascade')
    partner_id = fields.Many2one('res.partner', required=True)
    woo_customer_id = fields.Integer(index=True)
    woo_email = fields.Char()
    last_synced = fields.Datetime()
    company_id = fields.Many2one(
        'res.company', required=True, default=lambda self: self.env.company,
    )

    # ------------------------------------------------------------------
    # Helpers (Task 25)
    # ------------------------------------------------------------------

    @api.model
    def _find_or_create(self, instance, email, wc_data=None):
        """Find or create a woo.customer + res.partner for the given email.

        Args:
            instance: woo.instance record
            email: customer email address
            wc_data: optional dict with full WC customer payload

        Returns:
            woo.customer record
        """
        email = (email or '').strip().lower()
        if not email:
            return self.browse()

        wc_customer_id = (wc_data or {}).get('id', 0)

        # Check existing link
        if wc_customer_id:
            existing = self.search([
                ('instance_id', '=', instance.id),
                ('woo_customer_id', '=', wc_customer_id),
            ], limit=1)
            if existing:
                return existing

        # Check by email
        existing = self.search([
            ('instance_id', '=', instance.id),
            ('woo_email', '=ilike', email),
        ], limit=1)
        if existing:
            if wc_customer_id and not existing.woo_customer_id:
                existing.woo_customer_id = wc_customer_id
            return existing

        # Find or create partner
        partner = self.env['res.partner'].search([
            ('email', '=ilike', email),
            '|', ('company_id', '=', instance.company_id.id), ('company_id', '=', False),
        ], limit=1)

        if not partner:
            billing = (wc_data or {}).get('billing', {})
            partner_vals = instance._prepare_partner_vals(billing) if billing else {
                'name': email.split('@')[0].title(),
                'email': email,
                'company_id': instance.company_id.id,
            }
            partner = self.env['res.partner'].create(partner_vals)

        # Create woo.customer link
        woo_cust = self.create({
            'instance_id': instance.id,
            'partner_id': partner.id,
            'woo_customer_id': wc_customer_id,
            'woo_email': email,
            'last_synced': fields.Datetime.now(),
            'company_id': instance.company_id.id,
        })

        instance._log_sync(
            'customer', 'woo_to_odoo', partner.display_name,
            'success', f'Customer created from WC (email: {email})',
        )
        return woo_cust
