from odoo import models, fields


class EncoachResource(models.Model):
    _name = 'encoach.resource'
    _description = 'Learning Resource'

    name = fields.Char(required=True)
    type = fields.Selection([
        ('video', 'Video'),
        ('pdf', 'PDF'),
        ('document', 'Document'),
        ('link', 'Link'),
        ('interactive', 'Interactive'),
    ])
    review_status = fields.Selection([
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    ], default='approved')
    subject_id = fields.Many2one('encoach.subject', ondelete='set null')
    topic_ids = fields.Many2many('encoach.topic')
    file = fields.Binary(attachment=True)
    url = fields.Char()
    difficulty = fields.Selection([
        ('beginner', 'Beginner'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced'),
    ])
    duration_minutes = fields.Integer()
    active = fields.Boolean(default=True)
    creator_id = fields.Many2one('res.users', default=lambda self: self.env.user)

    cefr_level = fields.Selection([
        ('pre_a1', 'Pre-A1'), ('a1', 'A1'), ('a2', 'A2'),
        ('b1', 'B1'), ('b2', 'B2'), ('c1', 'C1'), ('c2', 'C2'),
    ])
    grammar_topic = fields.Char(size=200)
    vocab_band = fields.Char(size=50)
    ai_generated = fields.Boolean(default=False)
    approved = fields.Boolean(default=False)
    ielts_certified = fields.Boolean(default=False)

    def to_api_dict(self):
        self.ensure_one()
        creator = self.creator_id
        return {
            'id': self.id,
            'name': self.name,
            'type': self.type or '',
            'resource_type': self.type or 'document',
            'subject_id': self.subject_id.id if self.subject_id else None,
            'topic_ids': self.topic_ids.ids,
            'topic_names': self.topic_ids.mapped('name'),
            'url': self.url or '',
            'has_file': bool(self.file),
            'difficulty': self.difficulty or '',
            'duration_minutes': self.duration_minutes,
            'author_id': creator.id if creator else None,
            'author_name': creator.name if creator else '',
            'is_published': bool(self.active),
            'review_status': self.review_status or 'approved',
            'cefr_level': self.cefr_level or '',
            'grammar_topic': self.grammar_topic or '',
            'vocab_band': self.vocab_band or '',
            'ai_generated': self.ai_generated,
            'approved': self.approved,
            'created_at': self.create_date.isoformat() if self.create_date else '',
            'file_name': self.name,
        }
