import base64
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, _paginate,
)

_logger = logging.getLogger(__name__)


def _ser_resource(r):
    tags = r.tag_ids if r.tag_ids else r.env['encoach.resource.tag']
    objectives = r.learning_objective_ids if r.learning_objective_ids else r.env['encoach.learning.objective']
    return {
        'id': r.id,
        'name': r.name or '',
        'resource_type': r.type or 'document',
        'type': r.type or 'document',
        'subject_id': r.subject_id.id if r.subject_id else None,
        'subject_name': r.subject_id.name if r.subject_id else '',
        'domain_id': r.domain_id.id if r.domain_id else None,
        'domain_name': r.domain_id.name if r.domain_id else '',
        'topic_ids': r.topic_ids.ids if r.topic_ids else [],
        'topic_names': r.topic_ids.mapped('name') if r.topic_ids else [],
        'learning_objective_ids': objectives.ids,
        'learning_objective_names': objectives.mapped('name'),
        'tag_ids': tags.ids,
        'tag_names': tags.mapped('name'),
        'tags': [{'id': t.id, 'name': t.name, 'color': t.color or '#6b7280'} for t in tags],
        'url': r.url or '',
        'has_file': bool(r.file),
        'difficulty': r.difficulty or '',
        'duration_minutes': r.duration_minutes or 0,
        'author_id': r.creator_id.id if r.creator_id else None,
        'author_name': r.creator_id.name if r.creator_id else '',
        'review_status': r.review_status or 'approved',
        'cefr_level': r.cefr_level or '',
        'ai_generated': r.ai_generated,
        'course_count': r.course_count or 0,
        'created_at': r.create_date.isoformat() if r.create_date else '',
    }


class ResourcesController(http.Controller):

    @http.route('/api/resources', type='http', auth='public', methods=['GET'], csrf=False)
    @jwt_required
    def list_resources(self, **kw):
        try:
            M = request.env['encoach.resource'].sudo()
            domain = []
            if kw.get('subject_id'):
                domain.append(('subject_id', '=', int(kw['subject_id'])))
            if kw.get('topic_id'):
                domain.append(('topic_ids', 'in', [int(kw['topic_id'])]))
            if kw.get('tag_id'):
                domain.append(('tag_ids', 'in', [int(kw['tag_id'])]))
            if kw.get('resource_type'):
                domain.append(('type', '=', kw['resource_type']))
            if kw.get('review_status'):
                domain.append(('review_status', '=', kw['review_status']))
            if kw.get('date_from'):
                domain.append(('create_date', '>=', kw['date_from']))
            if kw.get('date_to'):
                domain.append(('create_date', '<=', kw['date_to']))
            if kw.get('search'):
                domain.append(('name', 'ilike', kw['search']))
            offset, limit, page = _paginate(kw)
            total = M.search_count(domain)
            recs = M.search(domain, offset=offset, limit=limit, order='id desc')
            items = [_ser_resource(r) for r in recs]
            return _json_response({'items': items, 'data': items, 'total': total, 'page': page, 'size': limit})
        except Exception as e:
            _logger.exception('list_resources')
            return _error_response(str(e), 500)

    @http.route('/api/resources', type='http', auth='public', methods=['POST'], csrf=False)
    @jwt_required
    def create_resource(self, **kw):
        try:
            files = request.httprequest.files
            f = files.get('file')
            ct = request.httprequest.content_type or ''
            body = {}
            if 'application/json' in ct:
                body = _get_json_body()
            params = {**body, **kw}

            vals = {'name': params.get('name', f.filename if f else 'Resource')}
            rtype = params.get('resource_type') or params.get('type')
            if rtype:
                vals['type'] = rtype
            if params.get('subject_id'):
                vals['subject_id'] = int(params['subject_id'])
            if params.get('topic_id'):
                vals['topic_ids'] = [(4, int(params['topic_id']))]
            if params.get('topic_ids'):
                ids = params['topic_ids']
                if isinstance(ids, str):
                    ids = [int(x) for x in ids.split(',') if x.strip()]
                elif isinstance(ids, list):
                    ids = [int(x) for x in ids]
                vals['topic_ids'] = [(6, 0, ids)]
            if params.get('tag_ids'):
                ids = params['tag_ids']
                if isinstance(ids, str):
                    ids = [int(x) for x in ids.split(',') if x.strip()]
                elif isinstance(ids, list):
                    ids = [int(x) for x in ids]
                vals['tag_ids'] = [(6, 0, ids)]
            if params.get('domain_id'):
                vals['domain_id'] = int(params['domain_id'])
            if params.get('learning_objective_ids'):
                ids = params['learning_objective_ids']
                if isinstance(ids, str):
                    ids = [int(x) for x in ids.split(',') if x.strip()]
                elif isinstance(ids, list):
                    ids = [int(x) for x in ids]
                vals['learning_objective_ids'] = [(6, 0, ids)]
            if params.get('url'):
                vals['url'] = params['url']
            if params.get('difficulty'):
                vals['difficulty'] = params['difficulty']
            if params.get('cefr_level'):
                vals['cefr_level'] = params['cefr_level']
            if f:
                vals['file'] = base64.b64encode(f.read())
            rec = request.env['encoach.resource'].sudo().create(vals)
            return _json_response({'data': _ser_resource(rec)})
        except Exception as e:
            _logger.exception('create_resource')
            return _error_response(str(e), 500)

    @http.route('/api/resources/<int:rid>', type='http', auth='public', methods=['PATCH', 'PUT'], csrf=False)
    @jwt_required
    def update_resource(self, rid, **kw):
        try:
            rec = request.env['encoach.resource'].sudo().browse(rid)
            if not rec.exists():
                return _error_response('Not found', 404)
            body = _get_json_body()
            vals = {}
            for k in ('name', 'url', 'review_status', 'difficulty', 'cefr_level'):
                if k in body:
                    vals[k] = body[k]
            if 'resource_type' in body or 'type' in body:
                vals['type'] = body.get('resource_type') or body.get('type')
            if 'subject_id' in body:
                vals['subject_id'] = int(body['subject_id']) if body['subject_id'] else False
            if 'tag_ids' in body:
                ids = body['tag_ids']
                vals['tag_ids'] = [(6, 0, [int(i) for i in ids])] if ids else [(5,)]
            if 'domain_id' in body:
                vals['domain_id'] = int(body['domain_id']) if body['domain_id'] else False
            if 'topic_ids' in body:
                ids = body['topic_ids']
                vals['topic_ids'] = [(6, 0, [int(i) for i in ids])] if ids else [(5,)]
            elif 'topic_id' in body:
                vals['topic_ids'] = [(4, int(body['topic_id']))] if body['topic_id'] else [(5,)]
            if 'learning_objective_ids' in body:
                ids = body['learning_objective_ids']
                vals['learning_objective_ids'] = [(6, 0, [int(i) for i in ids])] if ids else [(5,)]
            if vals:
                rec.write(vals)
            return _json_response({'data': _ser_resource(rec)})
        except Exception as e:
            return _error_response(str(e), 500)

    @http.route('/api/resources/<int:rid>', type='http', auth='public', methods=['DELETE'], csrf=False)
    @jwt_required
    def delete_resource(self, rid, **kw):
        try:
            rec = request.env['encoach.resource'].sudo().browse(rid)
            if rec.exists():
                rec.unlink()
            return _json_response({'success': True})
        except Exception as e:
            return _error_response(str(e), 500)

    @http.route('/api/resources/<int:rid>/complete', type='http', auth='public', methods=['POST'], csrf=False)
    @jwt_required
    def mark_complete(self, rid, **kw):
        try:
            return _json_response({'data': {'id': rid, 'completed': True}})
        except Exception as e:
            return _error_response(str(e), 500)

    @http.route('/api/resources/<int:rid>/rate', type='http', auth='public', methods=['POST'], csrf=False)
    @jwt_required
    def rate_resource(self, rid, **kw):
        try:
            body = _get_json_body()
            return _json_response({'success': True, 'rating': body.get('rating', 0)})
        except Exception as e:
            return _error_response(str(e), 500)

    @http.route('/api/resources/<int:rid>/download', type='http', auth='public', methods=['GET'], csrf=False)
    @jwt_required
    def download_resource(self, rid, **kw):
        try:
            rec = request.env['encoach.resource'].sudo().browse(rid)
            if not rec.exists() or not rec.file:
                return _error_response('No file', 404)
            import mimetypes
            ext = (rec.name or '').rsplit('.', 1)[-1].lower() if '.' in (rec.name or '') else ''
            mime = mimetypes.types_map.get(f'.{ext}', 'application/octet-stream')
            data = base64.b64decode(rec.file)
            return request.make_response(data, [
                ('Content-Type', mime),
                ('Content-Disposition', f'attachment; filename="{rec.name}"'),
                ('Content-Length', str(len(data))),
            ])
        except Exception as e:
            _logger.exception('download_resource')
            return _error_response(str(e), 500)

    # ══════════════════════════════════════════════════════════════════
    # Resource Tags CRUD
    # ══════════════════════════════════════════════════════════════════

    @http.route('/api/resource-tags', type='http', auth='public', methods=['GET'], csrf=False)
    @jwt_required
    def list_tags(self, **kw):
        try:
            Tag = request.env['encoach.resource.tag'].sudo()
            domain = []
            if kw.get('search'):
                domain.append(('name', 'ilike', kw['search']))
            recs = Tag.search(domain, order='name')
            return _json_response({
                'data': [t.to_api_dict() for t in recs],
                'items': [t.to_api_dict() for t in recs],
            })
        except Exception as e:
            _logger.exception('list_tags')
            return _error_response(str(e), 500)

    @http.route('/api/resource-tags', type='http', auth='public', methods=['POST'], csrf=False)
    @jwt_required
    def create_tag(self, **kw):
        try:
            body = _get_json_body()
            vals = {'name': body.get('name', '').strip()}
            if not vals['name']:
                return _error_response('name is required', 400)
            if body.get('color'):
                vals['color'] = body['color']
            if body.get('description'):
                vals['description'] = body['description']
            rec = request.env['encoach.resource.tag'].sudo().create(vals)
            return _json_response({'data': rec.to_api_dict()}, 201)
        except Exception as e:
            _logger.exception('create_tag')
            return _error_response(str(e), 500)

    @http.route('/api/resource-tags/<int:tid>', type='http', auth='public',
                methods=['PATCH', 'PUT'], csrf=False)
    @jwt_required
    def update_tag(self, tid, **kw):
        try:
            rec = request.env['encoach.resource.tag'].sudo().browse(tid)
            if not rec.exists():
                return _error_response('Tag not found', 404)
            body = _get_json_body()
            vals = {}
            for k in ('name', 'color', 'description'):
                if k in body:
                    vals[k] = body[k]
            if vals:
                rec.write(vals)
            return _json_response({'data': rec.to_api_dict()})
        except Exception as e:
            return _error_response(str(e), 500)

    @http.route('/api/resource-tags/<int:tid>', type='http', auth='public',
                methods=['DELETE'], csrf=False)
    @jwt_required
    def delete_tag(self, tid, **kw):
        try:
            rec = request.env['encoach.resource.tag'].sudo().browse(tid)
            if rec.exists():
                rec.unlink()
            return _json_response({'success': True})
        except Exception as e:
            return _error_response(str(e), 500)
