# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

from odoo import models, fields, api, _


class FusionAccountsLog(models.Model):
    _name = 'fusion.accounts.log'
    _description = 'Fusion Accounts - Email Processing Log'
    _order = 'create_date desc'
    _rec_name = 'email_subject'

    email_from = fields.Char(
        string='From',
        readonly=True,
        help='Sender email address',
    )
    vendor_blocked = fields.Boolean(
        related='vendor_id.x_fa_block_email_bill',
        string='Vendor Blocked',
        readonly=True,
    )
    email_subject = fields.Char(
        string='Subject',
        readonly=True,
    )
    email_date = fields.Datetime(
        string='Email Date',
        readonly=True,
    )
    vendor_id = fields.Many2one(
        'res.partner',
        string='Matched Vendor',
        readonly=True,
        help='Vendor matched from sender email',
    )
    match_level = fields.Selection(
        selection=[
            ('exact_email', 'Exact Email'),
            ('domain', 'Domain Match'),
            ('name', 'Name Match'),
            ('no_match', 'No Match'),
        ],
        string='Match Level',
        readonly=True,
        help='How the vendor was identified',
    )
    action_taken = fields.Selection(
        selection=[
            ('bill_created', 'Bill Created'),
            ('blocked', 'Blocked (Vendor)'),
            ('failed', 'Failed'),
            ('no_vendor', 'No Vendor Match'),
        ],
        string='Action',
        readonly=True,
    )
    bill_id = fields.Many2one(
        'account.move',
        string='Created Bill',
        readonly=True,
        help='The vendor bill created from this email',
    )
    ai_extracted = fields.Boolean(
        string='AI Extracted',
        readonly=True,
        default=False,
        help='Whether AI data extraction was performed',
    )
    ai_result = fields.Text(
        string='AI Extraction Result',
        readonly=True,
        help='JSON output from AI extraction',
    )
    notes = fields.Text(
        string='Notes',
        readonly=True,
        help='Error messages or additional details',
    )

    def action_block_vendor(self):
        """Block the vendor from this log entry from email bill creation."""
        for log in self:
            if log.vendor_id and not log.vendor_id.x_fa_block_email_bill:
                log.vendor_id.write({'x_fa_block_email_bill': True})
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Vendor Blocked'),
                'message': _('Vendor blocked from email bill creation.'),
                'type': 'success',
                'sticky': False,
            }
        }

    def action_enable_vendor(self):
        """Enable the vendor from this log entry for email bill creation."""
        for log in self:
            if log.vendor_id and log.vendor_id.x_fa_block_email_bill:
                log.vendor_id.write({'x_fa_block_email_bill': False})
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Vendor Enabled'),
                'message': _('Vendor enabled for email bill creation.'),
                'type': 'success',
                'sticky': False,
            }
        }

    # Stat fields for dashboard
    @api.model
    def get_dashboard_data(self):
        """Return statistics for the dashboard."""
        today = fields.Date.today()
        return {
            'bills_pending': self.env['account.move'].search_count([
                ('move_type', '=', 'in_invoice'),
                ('state', '=', 'draft'),
                ('x_fa_created_from_email', '=', True),
            ]),
            'bills_today': self.search_count([
                ('action_taken', '=', 'bill_created'),
                ('create_date', '>=', fields.Datetime.to_string(today)),
            ]),
            'blocked_today': self.search_count([
                ('action_taken', '=', 'blocked'),
                ('create_date', '>=', fields.Datetime.to_string(today)),
            ]),
            'failed_today': self.search_count([
                ('action_taken', '=', 'failed'),
                ('create_date', '>=', fields.Datetime.to_string(today)),
            ]),
            'total_blocked_vendors': self.env['res.partner'].search_count([
                ('x_fa_block_email_bill', '=', True),
            ]),
        }
