from odoo import models, fields, api, _
from odoo.exceptions import ValidationError

class ReservationSchedule(models.Model):
    _name = 'reservation.schedule'
    _description = 'Restaurant Reservation Schedule'
    _order = 'day asc'

    day = fields.Selection([
        ('0', 'Monday'),
        ('1', 'Tuesday'),
        ('2', 'Wednesday'),
        ('3', 'Thursday'),
        ('4', 'Friday'),
        ('5', 'Saturday'),
        ('6', 'Sunday')
    ], string='Day of Week', required=True)
    
    opening_time = fields.Float(string='Opening Time', default=12.0, help="Format: 14.5 for 2:30 PM")
    closing_time = fields.Float(string='Closing Time', default=22.0)
    
    has_break = fields.Boolean(string='Has Break Time', default=False)
    break_start_time = fields.Float(string='Break Start Time')
    break_end_time = fields.Float(string='Break End Time')
    
    is_closed = fields.Boolean(string='Closed for Reservations', default=False)

    default_slot_duration = fields.Selection([
        ('0.5', '30 Minutes'),
        ('1.0', '1 Hour'),
        ('1.5', '1.5 Hours'),
        ('2.0', '2 Hours'),
        ('3.0', '3 Hours'),
    ], string='Default Slot Duration', default='1.0', required=True)

    peak_hour_ids = fields.One2many('reservation.peak.hour', 'schedule_id', string='Peak Hour Slot Overrides')

    display_opening = fields.Char(compute='_compute_display_times')
    display_closing = fields.Char(compute='_compute_display_times')
    display_break = fields.Char(compute='_compute_display_times')

    def _compute_display_times(self):
        for rec in self:
            rec.display_opening = self._float_to_time_str(rec.opening_time)
            rec.display_closing = self._float_to_time_str(rec.closing_time)
            if rec.has_break:
                rec.display_break = f"{self._float_to_time_str(rec.break_start_time)} - {self._float_to_time_str(rec.break_end_time)}"
            else:
                rec.display_break = ""

    def _float_to_time_str(self, time_float):
        hours = int(time_float)
        minutes = int((time_float - hours) * 60)
        ampm = "am" if hours < 12 else "pm"
        display_hours = hours if hours <= 12 else hours - 12
        if display_hours == 0: display_hours = 12
        return f"{display_hours}:{minutes:02d}{ampm}"

    _sql_constraints = [
        ('day_unique', 'unique(day)', 'Schedule for this day already exists!')
    ]

    @api.constrains('opening_time', 'closing_time', 'break_start_time', 'break_end_time', 'has_break')
    def _check_times(self):
        for rec in self:
            if not rec.is_closed:
                if rec.opening_time >= rec.closing_time:
                    raise ValidationError(_("Opening time must be before closing time."))
                if rec.has_break:
                    if not (rec.opening_time < rec.break_start_time < rec.break_end_time < rec.closing_time):
                        raise ValidationError(_("Break time must be within opening and closing hours, and start before it ends."))

    def name_get(self):
        result = []
        for rec in self:
            day_name = dict(self._fields['day'].selection).get(rec.day)
            result.append((rec.id, day_name))
        return result
