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

from odoo import models, fields


class FusionClockAIConversation(models.Model):
    _name = 'fusion.clock.ai.conversation'
    _description = 'AI Chat Conversation'
    _order = 'create_date desc'

    user_id = fields.Many2one('res.users', required=True, index=True, ondelete='cascade')
    conversation_type = fields.Selection([
        ('manager_query', 'Manager Query'),
        ('employee_chat', 'Employee Chat'),
        ('config', 'Configuration'),
    ], required=True)
    message_ids = fields.One2many('fusion.clock.ai.message', 'conversation_id')
    title = fields.Char(compute='_compute_title', store=True)
    company_id = fields.Many2one('res.company', default=lambda self: self.env.company)

    def _compute_title(self):
        for rec in self:
            first_msg = rec.message_ids.filtered(lambda m: m.role == 'user')[:1]
            if first_msg:
                text = first_msg.content[:60]
                rec.title = text + ('...' if len(first_msg.content) > 60 else '')
            else:
                rec.title = f"Conversation #{rec.id}"


class FusionClockAIMessage(models.Model):
    _name = 'fusion.clock.ai.message'
    _description = 'AI Chat Message'
    _order = 'create_date asc'

    conversation_id = fields.Many2one('fusion.clock.ai.conversation', required=True,
                                      ondelete='cascade', index=True)
    role = fields.Selection([
        ('system', 'System'),
        ('user', 'User'),
        ('assistant', 'Assistant'),
    ], required=True)
    content = fields.Text(required=True)
    token_count = fields.Integer()
