import json
import logging

from odoo import http
from odoo.http import request
from odoo.addons.encoach_api.controllers.base import (
    jwt_required, _json_response, _error_response, _get_json_body,
)

_logger = logging.getLogger(__name__)


class ExamStructureController(http.Controller):

    @http.route('/api/exam-structures', type='http', auth='none', methods=['GET'], csrf=False)
    @jwt_required
    def list_structures(self, **kw):
        domain = [('active', '=', True)]
        entity_id = kw.get('entity_id')
        if entity_id:
            domain.append(('entity_id', '=', int(entity_id)))

        limit = int(kw.get('limit', 50))
        offset = int(kw.get('offset', 0))
        records = request.env['encoach.exam.structure'].sudo().search(
            domain, limit=limit, offset=offset, order='create_date desc')
        total = request.env['encoach.exam.structure'].sudo().search_count(domain)

        items = []
        for r in records:
            modules = []
            if r.modules:
                try:
                    modules = json.loads(r.modules)
                except Exception:
                    modules = []
            items.append({
                'id': r.id,
                'name': r.name,
                'entity_id': r.entity_id.id if r.entity_id else None,
                'entity_name': r.entity_id.name if r.entity_id else None,
                'industry': r.industry or '',
                'modules': modules,
                'config': json.loads(r.config) if r.config else {},
            })

        return _json_response({'items': items, 'total': total})

    @http.route('/api/exam-structures', type='http', auth='none', methods=['POST'], csrf=False)
    @jwt_required
    def create_structure(self, **kw):
        body = _get_json_body()
        name = body.get('name')
        if not name:
            return _error_response('name is required', 400)

        vals = {
            'name': name,
            'industry': body.get('industry', ''),
            'modules': json.dumps(body.get('modules', [])),
            'config': json.dumps(body.get('config', {})),
        }
        entity_id = body.get('entity_id')
        if entity_id:
            vals['entity_id'] = int(entity_id)

        record = request.env['encoach.exam.structure'].sudo().create(vals)
        return _json_response({
            'id': record.id,
            'name': record.name,
            'entity_id': record.entity_id.id if record.entity_id else None,
            'industry': record.industry or '',
            'modules': json.loads(record.modules) if record.modules else [],
            'config': json.loads(record.config) if record.config else {},
        })

    @http.route('/api/exam-structures/<int:structure_id>', type='http', auth='none', methods=['PUT'], csrf=False)
    @jwt_required
    def update_structure(self, structure_id, **kw):
        record = request.env['encoach.exam.structure'].sudo().browse(structure_id)
        if not record.exists():
            return _error_response('Structure not found', 404)

        body = _get_json_body()
        vals = {}
        if 'name' in body:
            vals['name'] = body['name']
        if 'industry' in body:
            vals['industry'] = body['industry']
        if 'modules' in body:
            vals['modules'] = json.dumps(body['modules'])
        if 'config' in body:
            vals['config'] = json.dumps(body['config'])
        if 'entity_id' in body:
            vals['entity_id'] = int(body['entity_id']) if body['entity_id'] else False

        if vals:
            record.write(vals)

        modules = []
        if record.modules:
            try:
                modules = json.loads(record.modules)
            except Exception:
                modules = []

        return _json_response({
            'id': record.id,
            'name': record.name,
            'entity_id': record.entity_id.id if record.entity_id else None,
            'entity_name': record.entity_id.name if record.entity_id else None,
            'industry': record.industry or '',
            'modules': modules,
            'config': json.loads(record.config) if record.config else {},
        })

    @http.route('/api/exam-structures/<int:structure_id>', type='http', auth='none', methods=['DELETE'], csrf=False)
    @jwt_required
    def delete_structure(self, structure_id, **kw):
        record = request.env['encoach.exam.structure'].sudo().browse(structure_id)
        if not record.exists():
            return _error_response('Structure not found', 404)
        record.unlink()
        return _json_response({'success': True})
