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

import logging
from datetime import date, timedelta
from odoo import models, fields

_logger = logging.getLogger(__name__)


class ClockCorrectionAI(models.Model):
    _inherit = 'fusion.clock.correction'

    x_fclk_ai_advice = fields.Text(string='AI Review Advice', readonly=True)

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

        AI = self.env['fusion.clock.ai.service'].sudo()
        for correction in self:
            emp = correction.employee_id
            emp_context = AI._build_employee_context(
                emp, date.today() - timedelta(days=30), date.today()
            )
            correction_context = (
                f"Correction Request:\n"
                f"Employee: {emp.name}\n"
                f"Original check-in: {correction.original_check_in}\n"
                f"Original check-out: {correction.original_check_out}\n"
                f"Requested check-in: {correction.requested_check_in}\n"
                f"Requested check-out: {correction.requested_check_out}\n"
                f"Reason: {correction.reason}\n"
                f"State: {correction.state}\n"
                f"\nEmployee history:\n{emp_context}"
            )
            system_prompt = AI._get_system_prompt('correction_advisor')
            try:
                advice = AI.chat_completion(
                    [
                        {'role': 'system', 'content': system_prompt},
                        {'role': 'user', 'content': correction_context},
                    ],
                    feature='correction_advisor',
                )
                correction.write({'x_fclk_ai_advice': advice})
            except Exception as e:
                _logger.warning("AI advice failed for correction %s: %s", correction.id, e)
