from odoo import models, fields, api

class DockAuditPhase(models.TransientModel):
    _name = 'dock.audit.phase'
    _description = 'Phase Options'

    name = fields.Char("Phase Name")

class DockAuditReportWizard(models.TransientModel):
    _name = 'dock.audit.report'
    _description = 'Dock Audit Report Wizard'

    
    phase = fields.Integer(string="Phase", required=True)
   
    phaselist_id = fields.Many2one('dock.audit.phase', string="Phase List") #, required=True
    
    dock_audit = fields.Many2one('sos_dock_audit', string="Dock Audit")
    dock_audit_id = fields.Char(string="Dock Audit", required=True,readonly=True)
   

    @api.model
    def _get_phase_selection(self):
        phase_count = self.env.context.get('phase', 10)  # default 10 if not in context
        return [(str(i), f'Phase {i}') for i in range(1, phase_count + 1)]

    def action_generate_report(self):

        if not self.phaselist_id.name:
            # Do something if name is False, None, empty string, etc.
            phase_name = "all"
        else:
            phase_name = self.phaselist_id.name.replace("Phase ", "")

        #print(" Before generating report ")
        #print(f"phaselist: {self.phaselist_id.name}")

        try:
            return self.env.ref('sos_inventory.action_report_dock_audit').with_context(
            report_phase=phase_name
            ).report_action(self.dock_audit)

            print("Report action executed")
    
        except ValueError as e:
            print(f"Phase Version Not Found: {e}")



    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        phase_count = self.env.context.get('phase', 10)
        res['phase'] = phase_count

        # Check if phase records already exist
        existing_report = self.env['dock.audit.report'].search([])
        existing_phases = self.env['dock.audit.phase'].search([])
        if not existing_phases or len(existing_phases) != phase_count:
            # Optional: Clear only if mismatch
            existing_report.unlink()
            existing_phases.unlink()
            for i in range(1, phase_count + 1):
                self.env['dock.audit.phase'].create({'name': f'Phase {i}'})

        # Set default selected
        default_phase = self.env['dock.audit.phase'].search([('name', '=', f'Phase {phase_count}')], limit=1)
        res['phaselist_id'] = default_phase.id

        return res



