"""Training endpoints: vocabulary + grammar library + per-user progress."""
import logging
from odoo import http, fields as odoo_fields
from odoo.exceptions import ValidationError, UserError
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__)


def _user_error_status(e):
    """Translate Odoo validation errors into HTTP 400 instead of 500."""
    return 400 if isinstance(e, (ValidationError, UserError)) else 500


# ── Serializers ─────────────────────────────────────────────────────────
def _ser_vocab(v, progress=None):
    return {
        'id': v.id,
        'word': v.word or '',
        'meaning': v.meaning or '',
        'example_sentence': v.example_sentence or '',
        'level': v.level or 'B1',
        'part_of_speech': v.part_of_speech or 'noun',
        'category': v.category or 'general',
        'active': v.active,
        'learners_count': v.learners_count or 0,
        'completion_count': v.completion_count or 0,
        'completed': bool(progress and progress.completed),
        'mastery': (progress.mastery if progress else 'learning'),
        'last_reviewed': (progress.last_reviewed.isoformat() if progress and progress.last_reviewed else ''),
    }


def _ser_rule(r, progress=None):
    return {
        'id': r.id,
        'name': r.name or '',
        'description': r.description or '',
        'example': r.example or '',
        'level': r.level or 'B1',
        'category': r.category or 'general',
        'active': r.active,
        'learners_count': r.learners_count or 0,
        'completion_count': r.completion_count or 0,
        'completed': bool(progress and progress.completed),
        'last_reviewed': (progress.last_reviewed.isoformat() if progress and progress.last_reviewed else ''),
    }


def _domain_from_kw(kw, text_fields):
    domain = []
    if kw.get('level') and kw['level'] != 'all':
        domain.append(('level', '=', kw['level']))
    if kw.get('category') and kw['category'] != 'all':
        domain.append(('category', '=', kw['category']))
    active = kw.get('active')
    if active in ('true', 'false'):
        domain.append(('active', '=', active == 'true'))
    search = kw.get('search') or kw.get('q')
    if search and text_fields:
        terms = [(f, 'ilike', search) for f in text_fields]
        if len(terms) > 1:
            domain.extend(['|'] * (len(terms) - 1))
        domain.extend(terms)
    return domain


def _pager(kw):
    try:
        size = min(int(kw.get('size') or 100), 500)
    except (TypeError, ValueError):
        size = 100
    try:
        page = max(int(kw.get('page') or 1), 1)
    except (TypeError, ValueError):
        page = 1
    return size, page


# ── Vocabulary ──────────────────────────────────────────────────────────
class VocabularyController(http.Controller):

    @http.route('/api/training/vocabulary', type='http', auth='public',
                methods=['GET'], csrf=False)
    @jwt_required
    def list_vocab(self, **kw):
        try:
            Vocab = request.env['encoach.vocab.item'].sudo()
            domain = _domain_from_kw(kw, ['word', 'meaning', 'category'])
            size, page = _pager(kw)
            total = Vocab.search_count(domain)
            recs = Vocab.search(domain, limit=size, offset=(page - 1) * size)

            Progress = request.env['encoach.vocab.progress'].sudo()
            uid = request.env.user.id
            prog_map = {
                p.vocab_id.id: p for p in Progress.search([
                    ('user_id', '=', uid),
                    ('vocab_id', 'in', recs.ids),
                ])
            } if recs else {}

            items = [_ser_vocab(v, prog_map.get(v.id)) for v in recs]
            completed = sum(1 for i in items if i['completed'])
            return _json_response({
                'data': items, 'items': items, 'total': total,
                'summary': {
                    'total': total,
                    'completed': completed,
                    'remaining': total - completed,
                    'completion_rate': round((completed / total) * 100, 1) if total else 0.0,
                },
                'page': page, 'size': size,
            })
        except Exception as e:
            _logger.exception('list_vocab')
            return _error_response(str(e), 500)

    @http.route('/api/training/vocabulary', type='http', auth='public',
                methods=['POST'], csrf=False)
    @jwt_required
    def create_vocab(self, **kw):
        try:
            body = _get_json_body()
            if not body.get('word') or not body.get('meaning'):
                return _error_response('word and meaning are required', 400)
            vals = {
                'word': body['word'].strip(),
                'meaning': body['meaning'].strip(),
                'example_sentence': body.get('example_sentence') or '',
                'level': body.get('level') or 'B1',
                'part_of_speech': body.get('part_of_speech') or 'noun',
                'category': body.get('category') or 'general',
                'active': body.get('active', True),
            }
            rec = request.env['encoach.vocab.item'].sudo().create(vals)
            return _json_response(_ser_vocab(rec))
        except Exception as e:
            _logger.exception('create_vocab')
            return _error_response(str(e), _user_error_status(e))

    @http.route('/api/training/vocabulary/<int:vid>', type='http',
                auth='public', methods=['GET'], csrf=False)
    @jwt_required
    def get_vocab(self, vid, **kw):
        rec = request.env['encoach.vocab.item'].sudo().browse(vid)
        if not rec.exists():
            return _error_response('Not found', 404)
        prog = request.env['encoach.vocab.progress'].sudo().search([
            ('user_id', '=', request.env.user.id),
            ('vocab_id', '=', rec.id),
        ], limit=1)
        return _json_response(_ser_vocab(rec, prog))

    @http.route('/api/training/vocabulary/<int:vid>', type='http',
                auth='public', methods=['PATCH', 'PUT'], csrf=False)
    @jwt_required
    def update_vocab(self, vid, **kw):
        try:
            body = _get_json_body()
            rec = request.env['encoach.vocab.item'].sudo().browse(vid)
            if not rec.exists():
                return _error_response('Not found', 404)
            vals = {}
            for k in ('word', 'meaning', 'example_sentence', 'level',
                      'part_of_speech', 'category'):
                if k in body:
                    vals[k] = body[k]
            if 'active' in body:
                vals['active'] = bool(body['active'])
            if vals:
                rec.write(vals)
            return _json_response(_ser_vocab(rec))
        except Exception as e:
            _logger.exception('update_vocab')
            return _error_response(str(e), _user_error_status(e))

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

    @http.route('/api/training/vocabulary/<int:vid>/progress',
                type='http', auth='public',
                methods=['POST', 'PATCH'], csrf=False)
    @jwt_required
    def set_vocab_progress(self, vid, **kw):
        try:
            body = _get_json_body()
            rec = request.env['encoach.vocab.item'].sudo().browse(vid)
            if not rec.exists():
                return _error_response('Not found', 404)
            Progress = request.env['encoach.vocab.progress'].sudo()
            uid = request.env.user.id
            prog = Progress.search([
                ('user_id', '=', uid),
                ('vocab_id', '=', rec.id),
            ], limit=1)
            vals = {
                'user_id': uid,
                'vocab_id': rec.id,
                'last_reviewed': odoo_fields.Datetime.now(),
            }
            if 'completed' in body:
                vals['completed'] = bool(body['completed'])
            if body.get('mastery') in ('learning', 'familiar', 'mastered'):
                vals['mastery'] = body['mastery']
            if prog:
                vals['review_count'] = (prog.review_count or 0) + 1
                prog.write(vals)
            else:
                vals['review_count'] = 1
                prog = Progress.create(vals)
            return _json_response(_ser_vocab(rec, prog))
        except Exception as e:
            _logger.exception('set_vocab_progress')
            return _error_response(str(e), 500)


# ── Grammar ─────────────────────────────────────────────────────────────
class GrammarController(http.Controller):

    @http.route('/api/training/grammar', type='http', auth='public',
                methods=['GET'], csrf=False)
    @jwt_required
    def list_grammar(self, **kw):
        try:
            Rule = request.env['encoach.grammar.rule'].sudo()
            domain = _domain_from_kw(kw, ['name', 'description', 'category'])
            size, page = _pager(kw)
            total = Rule.search_count(domain)
            recs = Rule.search(domain, limit=size, offset=(page - 1) * size)

            Progress = request.env['encoach.grammar.progress'].sudo()
            uid = request.env.user.id
            prog_map = {
                p.rule_id.id: p for p in Progress.search([
                    ('user_id', '=', uid),
                    ('rule_id', 'in', recs.ids),
                ])
            } if recs else {}

            items = [_ser_rule(r, prog_map.get(r.id)) for r in recs]
            completed = sum(1 for i in items if i['completed'])
            return _json_response({
                'data': items, 'items': items, 'total': total,
                'summary': {
                    'total': total,
                    'completed': completed,
                    'remaining': total - completed,
                    'completion_rate': round((completed / total) * 100, 1) if total else 0.0,
                },
                'page': page, 'size': size,
            })
        except Exception as e:
            _logger.exception('list_grammar')
            return _error_response(str(e), 500)

    @http.route('/api/training/grammar', type='http', auth='public',
                methods=['POST'], csrf=False)
    @jwt_required
    def create_rule(self, **kw):
        try:
            body = _get_json_body()
            if not body.get('name') or not body.get('description'):
                return _error_response('name and description are required', 400)
            vals = {
                'name': body['name'].strip(),
                'description': body['description'].strip(),
                'example': body.get('example') or '',
                'level': body.get('level') or 'B1',
                'category': body.get('category') or 'general',
                'active': body.get('active', True),
            }
            rec = request.env['encoach.grammar.rule'].sudo().create(vals)
            return _json_response(_ser_rule(rec))
        except Exception as e:
            _logger.exception('create_rule')
            return _error_response(str(e), _user_error_status(e))

    @http.route('/api/training/grammar/<int:rid>', type='http',
                auth='public', methods=['GET'], csrf=False)
    @jwt_required
    def get_rule(self, rid, **kw):
        rec = request.env['encoach.grammar.rule'].sudo().browse(rid)
        if not rec.exists():
            return _error_response('Not found', 404)
        prog = request.env['encoach.grammar.progress'].sudo().search([
            ('user_id', '=', request.env.user.id),
            ('rule_id', '=', rec.id),
        ], limit=1)
        return _json_response(_ser_rule(rec, prog))

    @http.route('/api/training/grammar/<int:rid>', type='http',
                auth='public', methods=['PATCH', 'PUT'], csrf=False)
    @jwt_required
    def update_rule(self, rid, **kw):
        try:
            body = _get_json_body()
            rec = request.env['encoach.grammar.rule'].sudo().browse(rid)
            if not rec.exists():
                return _error_response('Not found', 404)
            vals = {}
            for k in ('name', 'description', 'example', 'level', 'category'):
                if k in body:
                    vals[k] = body[k]
            if 'active' in body:
                vals['active'] = bool(body['active'])
            if vals:
                rec.write(vals)
            return _json_response(_ser_rule(rec))
        except Exception as e:
            _logger.exception('update_rule')
            return _error_response(str(e), _user_error_status(e))

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

    @http.route('/api/training/grammar/<int:rid>/progress',
                type='http', auth='public',
                methods=['POST', 'PATCH'], csrf=False)
    @jwt_required
    def set_rule_progress(self, rid, **kw):
        try:
            body = _get_json_body()
            rec = request.env['encoach.grammar.rule'].sudo().browse(rid)
            if not rec.exists():
                return _error_response('Not found', 404)
            Progress = request.env['encoach.grammar.progress'].sudo()
            uid = request.env.user.id
            prog = Progress.search([
                ('user_id', '=', uid),
                ('rule_id', '=', rec.id),
            ], limit=1)
            vals = {
                'user_id': uid,
                'rule_id': rec.id,
                'last_reviewed': odoo_fields.Datetime.now(),
            }
            if 'completed' in body:
                vals['completed'] = bool(body['completed'])
            if prog:
                vals['review_count'] = (prog.review_count or 0) + 1
                prog.write(vals)
            else:
                vals['review_count'] = 1
                prog = Progress.create(vals)
            return _json_response(_ser_rule(rec, prog))
        except Exception as e:
            _logger.exception('set_rule_progress')
            return _error_response(str(e), 500)
