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

_logger = logging.getLogger(__name__)

class ResPartner(models.Model):
    _inherit = 'res.partner'

    image_face_1 = fields.Binary("Face Image 1", attachment=True)
    image_face_2 = fields.Binary("Face Image 2", attachment=True)
    image_face_3 = fields.Binary("Face Image 3", attachment=True)

    def _sync_face_images(self):
        # Get the server URL from any POS config that has it configured
        pos_config = self.env['pos.config'].search([('pos_face_rec_server_url', '!=', False)], limit=1)
        if not pos_config or not pos_config.pos_face_rec_server_url:
            _logger.warning("Face Recognition Server URL is not configured in any POS configuration")
            return
        
        server_url = pos_config.pos_face_rec_server_url

        for partner in self:
            # Only sync if at least one image is present
            if not any([partner.image_face_1, partner.image_face_2, partner.image_face_3]):
                continue

            images = [
                partner.image_face_1.decode('utf-8') if isinstance(partner.image_face_1, bytes) else partner.image_face_1,
                partner.image_face_2.decode('utf-8') if isinstance(partner.image_face_2, bytes) else partner.image_face_2,
                partner.image_face_3.decode('utf-8') if isinstance(partner.image_face_3, bytes) else partner.image_face_3
            ]
            
            payload = {
                'partner_id': partner.id,
                'name': partner.name,
                'images': images
            }
            
            try:
                # Remove trailing slash if present
                base_url = server_url.rstrip('/')
                requests.post(f"{base_url}/train", json=payload, timeout=5)
            except Exception as e:
                _logger.error(f"Failed to sync face images for partner {partner.id}: {e}")

    @api.model_create_multi
    def create(self, vals_list):
        partners = super().create(vals_list)
        partners._sync_face_images()
        return partners

    def write(self, vals):
        res = super().write(vals)
        if any(f in vals for f in ['image_face_1', 'image_face_2', 'image_face_3', 'name']):
            self._sync_face_images()
        return res

    def get_top_products(self):
        self.ensure_one()
        # Simple implementation: get top 3 products by quantity from past orders
        query = """
            SELECT pt.name, sum(pol.qty) as qty
            FROM pos_order_line pol
            JOIN pos_order po ON pol.order_id = po.id
            JOIN product_product pp ON pol.product_id = pp.id
            JOIN product_template pt ON pp.product_tmpl_id = pt.id
            WHERE po.partner_id = %s
            GROUP BY pt.name
            ORDER BY qty DESC
            LIMIT 3
        """
        self.env.cr.execute(query, (self.id,))
        return [{'name': row[0], 'qty': row[1]} for row in self.env.cr.fetchall()]
