import uuid
import logging

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

_logger = logging.getLogger(__name__)


class KycApplication(models.Model):
    _name = 'kyc.application'
    _description = 'KYC Application'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc'

    name = fields.Char(
        'Reference',
        required=True,
        copy=False,
        readonly=True,
        default=lambda self: _('New'),
    )
    workflow_id = fields.Char(
        'Temporal Workflow ID',
        index=True,
        tracking=True,
        help='UUID from Temporal workflow',
    )
    team_name = fields.Char(
        'Team Name',
        required=True,
        tracking=True,
    )
    owner_id = fields.Char(
        'Owner ID',
        required=True,
        help='User ID in Logto',
    )

    # State
    state = fields.Selection([
        ('pending', 'Pending Review'),
        ('in_review', 'In Review'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    ], string='Status', default='pending', required=True, tracking=True)

    @api.model
    def _expand_states(self, states, domain, order):
        """Return all possible states for kanban view."""
        return [key for key, val in type(self).state.selection]

    # KYC Score
    score = fields.Integer(
        'KYC Score',
        default=0,
        help='Score from 0 to 100',
        tracking=True,
    )

    # 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 info
    contact_person = fields.Char('Contact Person')
    contact_email = fields.Char('Contact Email')
    contact_phone = fields.Char('Contact Phone')

    # Review
    reviewer_id = fields.Many2one('res.users', 'Reviewer', tracking=True)
    review_notes = fields.Html('Review Notes')
    reviewed_date = fields.Datetime('Review Date')

    # Dates
    submitted_date = fields.Datetime(
        'Submitted Date',
        default=fields.Datetime.now,
    )
    approved_date = fields.Datetime('Approved Date')

    # Created buyer
    buyer_id = fields.Many2one(
        'buyer',
        'Created Buyer',
        readonly=True,
    )

    _sql_constraints = [
        ('unique_workflow_id', 'UNIQUE(workflow_id)', 'Workflow ID must be unique!'),
    ]

    @api.model
    def create(self, vals):
        if vals.get('name', _('New')) == _('New'):
            vals['name'] = self.env['ir.sequence'].sudo().next_by_code('kyc.application') or _('New')
        if not vals.get('submitted_date'):
            vals['submitted_date'] = fields.Datetime.now()
        return super().create(vals)

    @api.constrains('score')
    def _check_score(self):
        for record in self:
            if not (0 <= record.score <= 100):
                raise ValidationError(_('KYC Score must be between 0 and 100'))

    def action_start_review(self):
        """Start reviewing the application."""
        self.ensure_one()
        if self.state != 'pending':
            raise ValidationError(_('Can only start review for pending applications'))
        self.write({
            'state': 'in_review',
            'reviewer_id': self.env.user.id,
        })

    def action_approve(self):
        """Approve the application and create a buyer."""
        self.ensure_one()
        if self.state not in ('pending', 'in_review'):
            raise ValidationError(_('Can only approve pending or in-review applications'))
        if self.score < 60:
            raise ValidationError(_('Score must be at least 60 to approve'))
        if self.buyer_id:
            raise ValidationError(_('Buyer already created for this application'))

        # Create buyer from application data
        # buyer.uuid will be used as team_uuid when Temporal creates team
        buyer = self.env['buyer'].create({
            'team_name': self.team_name,
            'tax_id': self.tax_id,
            'registration_number': self.registration_number,
            'country_id': self.country_id.id if self.country_id else False,
            'contact_person': self.contact_person,
            'contact_email': self.contact_email,
            'contact_phone': self.contact_phone,
            'application_id': self.id,
            'workflow_id': self.workflow_id,
            'state': 'pending',
        })

        self.write({
            'state': 'approved',
            'buyer_id': buyer.id,
            'reviewer_id': self.env.user.id,
            'reviewed_date': fields.Datetime.now(),
            'approved_date': fields.Datetime.now(),
        })

        _logger.info(f"KYC application {self.name} approved, buyer {buyer.name} created")
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'buyer',
            'res_id': buyer.id,
            'view_mode': 'form',
            'target': 'current',
        }

    def action_reject(self):
        """Reject the application."""
        self.ensure_one()
        if self.state not in ('pending', 'in_review'):
            raise ValidationError(_('Can only reject pending or in-review applications'))
        if not self.review_notes:
            raise ValidationError(_('Review notes are required when rejecting'))

        self.write({
            'state': 'rejected',
            'reviewer_id': self.env.user.id,
            'reviewed_date': fields.Datetime.now(),
        })

        _logger.info(f"KYC application {self.name} rejected")

    def action_view_buyer(self):
        """Open the related buyer record."""
        self.ensure_one()
        if not self.buyer_id:
            return
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'buyer',
            'res_id': self.buyer_id.id,
            'view_mode': 'form',
            'target': 'current',
        }
