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

import logging
from odoo import models, fields

_logger = logging.getLogger(__name__)


class ClockReportAI(models.Model):
    _inherit = 'fusion.clock.report'

    x_fclk_ai_narrative = fields.Text(string='AI Narrative', readonly=True)

    def action_generate_ai_narrative(self):
        ICP = self.env['ir.config_parameter'].sudo()
        if ICP.get_param('fusion_clock_ai.enable_narrative_reports', 'True') != 'True':
            return

        AI = self.env['fusion.clock.ai.service'].sudo()
        for report in self:
            context_data = AI._build_payroll_context(report)
            system_prompt = AI._get_system_prompt('weekly_narrative')
            try:
                narrative = AI.chat_completion(
                    [
                        {'role': 'system', 'content': system_prompt},
                        {'role': 'user', 'content': context_data},
                    ],
                    feature='report_narrative',
                )
                report.write({'x_fclk_ai_narrative': narrative})
            except Exception as e:
                _logger.warning("AI narrative failed for report %s: %s", report.name, e)

    def action_generate_report(self):
        result = super().action_generate_report()
        self.action_generate_ai_narrative()
        return result
