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

from odoo import models, fields, api


class FusionApiUsage(models.Model):
    _name = 'fusion.api.usage'
    _description = 'API Usage Log'
    _order = 'create_date desc'
    _rec_name = 'display_name'

    consumer_id = fields.Many2one(
        'fusion.api.consumer', required=True, index=True, ondelete='cascade',
    )
    provider_id = fields.Many2one(
        'fusion.api.provider', required=True, index=True, ondelete='cascade',
    )
    user_id = fields.Many2one('res.users', index=True, ondelete='set null')

    feature = fields.Char(index=True, help='Feature label, e.g. invoice_extraction')
    model_name = fields.Char(string='AI Model', help='e.g. gpt-4o, claude-3-5-sonnet')

    tokens_in = fields.Integer(string='Input Tokens')
    tokens_out = fields.Integer(string='Output Tokens')
    total_tokens = fields.Integer(
        compute='_compute_total_tokens', store=True, string='Total Tokens',
    )
    estimated_cost_usd = fields.Float(digits=(10, 6), string='Cost (USD)')
    response_time_ms = fields.Integer(string='Response Time (ms)')

    status = fields.Selection([
        ('success', 'Success'),
        ('error', 'Error'),
        ('rate_limited', 'Rate Limited'),
        ('budget_exceeded', 'Budget Exceeded'),
    ], default='success', required=True, index=True)
    error_message = fields.Text()

    company_id = fields.Many2one('res.company', default=lambda self: self.env.company)
    display_name = fields.Char(compute='_compute_display_name')

    @api.depends('tokens_in', 'tokens_out')
    def _compute_total_tokens(self):
        for rec in self:
            rec.total_tokens = rec.tokens_in + rec.tokens_out

    def _compute_display_name(self):
        for rec in self:
            consumer = rec.consumer_id.name or 'Unknown'
            provider = rec.provider_id.name or 'Unknown'
            rec.display_name = f"{consumer} - {provider} ({rec.status})"
