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

import logging

from odoo import fields, models

_logger = logging.getLogger(__name__)


class ResConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    # ------------------------------------------------------------------
    # API Configuration
    # ------------------------------------------------------------------

    fn_openai_api_key = fields.Char(
        string='OpenAI API Key',
        config_parameter='fusion_notes.openai_api_key',
        help='OpenAI API key for Whisper transcription and GPT formatting. '
             'Get your key at https://platform.openai.com',
    )
    fn_ai_model = fields.Selection(
        selection=[
            ('gpt-4o-mini', 'GPT-4o Mini (Fast, Low Cost)'),
            ('gpt-4o', 'GPT-4o (Best Quality)'),
            ('gpt-4.1-mini', 'GPT-4.1 Mini'),
            ('gpt-4.1', 'GPT-4.1'),
        ],
        string='AI Formatting Model',
        config_parameter='fusion_notes.ai_model',
        help='Model used for formatting voice notes into professional text',
    )

    # ------------------------------------------------------------------
    # Default Preferences
    # ------------------------------------------------------------------

    fn_default_review_mode = fields.Boolean(
        string='Review Before Posting',
        config_parameter='fusion_notes.default_review_mode',
        help='Show transcribed text for review and editing before posting. '
             'If disabled, notes are posted immediately after transcription.',
    )
    fn_default_ai_format = fields.Boolean(
        string='AI Format by Default',
        config_parameter='fusion_notes.default_ai_format',
        help='Automatically format transcribed text with AI before review. '
             'Users can still toggle this per note.',
    )
    fn_max_recording_seconds = fields.Integer(
        string='Max Recording Duration (seconds)',
        config_parameter='fusion_notes.max_recording_seconds',
        help='Maximum recording duration in seconds (default: 300 = 5 minutes)',
    )

    def set_values(self):
        ICP = self.env['ir.config_parameter'].sudo()
        # Protect API key from accidental blanking
        _protected = {
            'fusion_notes.openai_api_key': ICP.get_param('fusion_notes.openai_api_key', ''),
            'fusion_notes.ai_model': ICP.get_param('fusion_notes.ai_model', ''),
            'fusion_notes.max_recording_seconds': ICP.get_param('fusion_notes.max_recording_seconds', ''),
        }
        super().set_values()
        for key, old_val in _protected.items():
            new_val = ICP.get_param(key, '')
            if not new_val and old_val:
                ICP.set_param(key, old_val)
                _logger.warning("Settings protection: restored %s", key)
