import uuid
import asyncio
import logging
import os

from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)

TEMPORAL_HOST = os.environ.get('TEMPORAL_HOST', 'temporal:7233')
TEMPORAL_NAMESPACE = os.environ.get('TEMPORAL_NAMESPACE', 'default')


class Buyer(models.Model):
    _name = 'buyer'
    _description = 'Buyer'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc'

    name = fields.Char(
        'Reference',
        required=True,
        copy=False,
        readonly=True,
        default=lambda self: _('New'),
    )
    uuid = fields.Char(
        'UUID',
        required=True,
        readonly=True,
        default=lambda self: str(uuid.uuid4()),
        index=True,
    )
    team_name = fields.Char(
        'Team Name',
        required=True,
        tracking=True,
    )
    logto_org_id = fields.Char(
        'Logto Organization ID',
        readonly=True,
        index=True,
        tracking=True,
        help='Set after Logto org creation',
    )

    # Company data
    tax_id = fields.Char('Tax ID', tracking=True)
    registration_number = fields.Char('Registration Number', tracking=True)
    country_id = fields.Many2one('res.country', 'Country', tracking=True)

    # Contact
    contact_person = fields.Char('Contact Person')
    contact_email = fields.Char('Contact Email')
    contact_phone = fields.Char('Contact Phone')

    # Status
    state = fields.Selection([
        ('pending', 'Pending Logto'),
        ('active', 'Active'),
        ('suspended', 'Suspended'),
    ], string='Status', default='pending', required=True, tracking=True)

    is_active = fields.Boolean('Active', default=True)
    joined_date = fields.Date(
        'Joined Date',
        default=fields.Date.today,
        tracking=True,
    )

    # Link to application
    application_id = fields.Many2one(
        'kyc.application',
        'KYC Application',
        readonly=True,
    )
    workflow_id = fields.Char(
        'Temporal Workflow ID',
        readonly=True,
        help='Workflow ID from application',
    )

    _sql_constraints = [
        ('unique_uuid', 'UNIQUE(uuid)', 'UUID must be unique!'),
    ]

    @api.model
    def create(self, vals):
        if vals.get('name', _('New')) == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('buyer') or _('New')
        return super().create(vals)

    def action_create_logto_org(self):
        """Send signal to Temporal workflow to create Logto organization."""
        self.ensure_one()
        if not self.workflow_id:
            raise ValidationError(_('No workflow ID associated with this buyer'))
        if self.logto_org_id:
            raise ValidationError(_('Logto organization already created'))

        try:
            asyncio.run(self._send_approve_signal())
            _logger.info(f"Sent approve signal for buyer {self.name}")
        except Exception as e:
            _logger.error(f"Error sending approve signal: {e}")
            raise ValidationError(_(f"Failed to send signal: {e}"))

    async def _send_approve_signal(self):
        """Async method to send approval signal to Temporal."""
        from temporalio.client import Client

        client = await Client.connect(TEMPORAL_HOST, namespace=TEMPORAL_NAMESPACE)
        handle = client.get_workflow_handle(self.workflow_id)

        await handle.signal(
            "approve_kyc",
            {
                "approved_by": str(self.env.user.id),
                "notes": f"Buyer {self.name} created",
            },
        )

    def set_logto_org_id(self, logto_org_id):
        """Called by Temporal activity after Logto org creation."""
        self.ensure_one()
        self.write({
            'logto_org_id': logto_org_id,
            'state': 'active',
        })
        _logger.info(f"Buyer {self.name} activated with Logto org {logto_org_id}")

    def name_get(self):
        result = []
        for buyer in self:
            name = f"{buyer.name} - {buyer.team_name}"
            result.append((buyer.id, name))
        return result

    def action_view_application(self):
        """Open the related KYC application."""
        self.ensure_one()
        if not self.application_id:
            return
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'kyc.application',
            'res_id': self.application_id.id,
            'view_mode': 'form',
            'target': 'current',
        }
