# -*- coding: utf-8 -*-
"""
Disable database expiration checks and registration.
Consolidates all ir.config_parameter overrides.
"""

import logging
from datetime import datetime
from odoo import api, models, fields

_logger = logging.getLogger(__name__)


class IrConfigParameter(models.Model):
    """Override config parameters to prevent expiration and protect license values."""
    _inherit = 'ir.config_parameter'

    PROTECTED_PARAMS = {
        'database.expiration_date': '2099-12-31 23:59:59',
        'database.expiration_reason': 'renewal',
        'database.enterprise_code': 'PERMANENT_LOCAL',
    }
    
    CLEAR_PARAMS = [
        'database.already_linked_subscription_url',
        'database.already_linked_email',
        'database.already_linked_send_mail_url',
    ]

    def init(self, force=False):
        """Set permanent valid subscription on module init."""
        super().init(force=force)
        self._set_permanent_subscription()

    @api.model
    def _set_permanent_subscription(self):
        """Set database to never expire."""
        _logger.info("Setting permanent subscription values...")
        
        for key, value in self.PROTECTED_PARAMS.items():
            try:
                self.env.cr.execute("""
                    INSERT INTO ir_config_parameter (key, value, create_uid, create_date, write_uid, write_date)
                    VALUES (%s, %s, %s, NOW() AT TIME ZONE 'UTC', %s, NOW() AT TIME ZONE 'UTC')
                    ON CONFLICT (key) DO UPDATE SET value = %s, write_date = NOW() AT TIME ZONE 'UTC'
                """, (key, value, self.env.uid, self.env.uid, value))
            except Exception as e:
                _logger.debug("Could not set param %s: %s", key, e)
        
        for key in self.CLEAR_PARAMS:
            try:
                self.env.cr.execute("""
                    INSERT INTO ir_config_parameter (key, value, create_uid, create_date, write_uid, write_date)
                    VALUES (%s, '', %s, NOW() AT TIME ZONE 'UTC', %s, NOW() AT TIME ZONE 'UTC')
                    ON CONFLICT (key) DO UPDATE SET value = '', write_date = NOW() AT TIME ZONE 'UTC'
                """, (key, self.env.uid, self.env.uid))
            except Exception as e:
                _logger.debug("Could not clear param %s: %s", key, e)

    @api.model
    def get_param(self, key, default=False):
        """Override get_param to return permanent values for protected params."""
        if key in self.PROTECTED_PARAMS:
            return self.PROTECTED_PARAMS[key]
        
        if key in self.CLEAR_PARAMS:
            return ''
        
        return super().get_param(key, default)

    def set_param(self, key, value):
        """Override set_param to prevent external processes from changing protected values."""
        if key in self.PROTECTED_PARAMS:
            if value != self.PROTECTED_PARAMS[key]:
                _logger.warning("Blocked attempt to change protected param %s to %s", key, value)
                return True
        
        if key in self.CLEAR_PARAMS:
            value = ''
        
        return super().set_param(key, value)


class DatabaseExpirationCheck(models.AbstractModel):
    _name = 'disable.odoo.online.expiration'
    _description = 'Database Expiration Blocker'

    @api.model
    def check_database_expiration(self):
        return {
            'valid': True,
            'expiration_date': '2099-12-31 23:59:59',
            'expiration_reason': 'renewal',
        }


class Base(models.AbstractModel):
    _inherit = 'base'

    @api.model
    def _get_database_expiration_date(self):
        return datetime(2099, 12, 31, 23, 59, 59)

    @api.model  
    def _check_database_enterprise_expiration(self):
        return True
