import json

from odoo import models, fields, api


class EncoachStudentProfile(models.Model):
    _name = 'encoach.student.profile'
    _description = 'Student Onboarding Profile'

    user_id = fields.Many2one('res.users', required=True, ondelete='cascade', index=True)
    cefr_level = fields.Selection([
        ('pre_a1', 'Pre-A1'),
        ('a1', 'A1'),
        ('a2', 'A2'),
        ('b1', 'B1'),
        ('b2', 'B2'),
        ('c1', 'C1'),
        ('c2', 'C2'),
    ])
    target_band = fields.Float()
    learning_style = fields.Text(help='JSON array of styles: visual, audio, reading, mixed')
    learning_goal = fields.Char(size=200)
    hours_per_week = fields.Integer()
    study_mode = fields.Selection([
        ('self_study', 'Self Study'),
        ('with_teacher', 'With Teacher'),
    ])
    exam_date = fields.Date()
    placement_completed = fields.Boolean(default=False)
    placement_decision = fields.Selection([
        ('take_now', 'Take Now'),
        ('skip', 'Skip'),
    ])
    entity_id = fields.Many2one('encoach.entity', ondelete='set null')

    def get_learning_styles(self):
        """Return learning_style as a Python list."""
        self.ensure_one()
        if not self.learning_style:
            return []
        try:
            return json.loads(self.learning_style)
        except (json.JSONDecodeError, TypeError):
            return [self.learning_style] if self.learning_style else []

    def set_learning_styles(self, styles):
        """Accept a list of styles and store as JSON."""
        self.ensure_one()
        if isinstance(styles, list):
            self.learning_style = json.dumps(styles)
        elif isinstance(styles, str):
            self.learning_style = json.dumps([styles])
