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

import logging
from odoo import models, api

_logger = logging.getLogger(__name__)


class HrAttendanceAI(models.Model):
    _inherit = 'hr.attendance'

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

        AI = self.env['fusion.clock.ai.service'].sudo()
        system_prompt = AI._get_system_prompt('incident_explanation')

        context = (
            f"Incident type: {log_record.log_type}\n"
            f"Employee: {log_record.employee_id.name}\n"
            f"Date/Time: {log_record.log_date}\n"
            f"Location: {log_record.location_id.name or 'N/A'}\n"
            f"Distance: {log_record.distance or 0:.0f}m\n"
            f"Current description: {log_record.description or 'None'}\n"
        )

        shift = log_record.employee_id.x_fclk_shift_id
        if shift:
            context += f"Shift: {shift.name} ({shift.start_time:.1f}-{shift.end_time:.1f})\n"

        try:
            explanation = AI.chat_completion(
                [
                    {'role': 'system', 'content': system_prompt},
                    {'role': 'user', 'content': context},
                ],
                feature='incident_explain',
            )
            log_record.sudo().write({'description': explanation})
        except Exception as e:
            _logger.debug("AI incident explain skipped: %s", e)
