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

import base64
import logging

from odoo import api, fields, models
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)


class FusionXmlImportWizard(models.TransientModel):
    _name = 'fusion.xml.import.wizard'
    _description = 'Import ADP XML Files'

    xml_files = fields.Many2many(
        'ir.attachment', string='XML Files',
        help='Select one or more ADP XML data files to import',
    )
    result_message = fields.Text(string='Import Results', readonly=True)
    state = fields.Selection([
        ('draft', 'Upload'),
        ('done', 'Done'),
    ], default='draft')

    def action_import(self):
        """Process uploaded XML files and create client profiles."""
        self.ensure_one()
        if not self.xml_files:
            raise UserError('Please upload at least one XML file.')

        parser = self.env['fusion.xml.parser']
        created = 0
        updated = 0
        errors = []

        for attachment in self.xml_files:
            try:
                xml_content = base64.b64decode(attachment.datas).decode('utf-8')

                # Check if profile already exists by parsing health card from XML
                import xml.etree.ElementTree as ET
                try:
                    root = ET.fromstring(xml_content)
                except ET.ParseError:
                    errors.append(f'{attachment.name}: Could not parse XML')
                    continue
                form = root.find('Form')
                if form is None:
                    errors.append(f'{attachment.name}: No Form element in XML')
                    continue

                s1 = form.find('section1')
                health_card = ''
                if s1 is not None:
                    hc_el = s1.find('healthNo')
                    if hc_el is not None and hc_el.text:
                        health_card = hc_el.text.strip()

                existing = False
                if health_card:
                    existing = self.env['fusion.client.profile'].search([
                        ('health_card_number', '=', health_card),
                    ], limit=1)

                profile, app_data = parser.parse_and_create(xml_content)
                if not profile:
                    errors.append(f'{attachment.name}: Could not create profile')
                    continue

                if existing:
                    updated += 1
                else:
                    created += 1

                _logger.info(
                    'Imported XML %s -> Profile: %s (ID: %s)',
                    attachment.name, profile.display_name, profile.id,
                )
            except Exception as e:
                errors.append(f'{attachment.name}: {str(e)}')
                _logger.exception('Error importing XML file %s', attachment.name)

        # Build result message
        lines = [
            f'Import Complete!',
            f'- Profiles created: {created}',
            f'- Profiles updated: {updated}',
            f'- Total files processed: {created + updated}',
        ]
        if errors:
            lines.append(f'\nErrors ({len(errors)}):')
            for err in errors:
                lines.append(f'  - {err}')

        self.result_message = '\n'.join(lines)
        self.state = 'done'

        return {
            'type': 'ir.actions.act_window',
            'res_model': 'fusion.xml.import.wizard',
            'view_mode': 'form',
            'res_id': self.id,
            'target': 'new',
        }
