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

_logger = logging.getLogger(__name__)


class EncoachScoreReleaseController(http.Controller):

    # ------------------------------------------------------------------
    # GET /api/scores/pending
    # ------------------------------------------------------------------
    @http.route('/api/scores/pending', type='http', auth='none',
                methods=['GET'], csrf=False)
    @jwt_required
    def get_pending(self, **kw):
        try:
            user = request.env.user.sudo()
            domain = [('status', '=', 'pending_approval')]

            if user.entity_ids:
                domain.append(('entity_id', 'in', user.entity_ids.ids))

            page = int(kw.get('page', 1))
            size = int(kw.get('size', 20))

            Attempt = request.env['encoach.student.attempt'].sudo()
            attempts, total = _paginate(Attempt, domain, page, size, order='completed_at desc')

            items = []
            for att in attempts:
                items.append({
                    'attempt_id': att.id,
                    'student_id': att.student_id.id,
                    'student_name': att.student_id.name or '',
                    'exam_id': att.exam_id.id if att.exam_id else None,
                    'exam_name': att.exam_id.title if att.exam_id else '',
                    'entity_id': att.entity_id.id if att.entity_id else None,
                    'completed_at': att.completed_at,
                    'listening_band': att.listening_band,
                    'reading_band': att.reading_band,
                    'writing_band': att.writing_band,
                    'speaking_band': att.speaking_band,
                    'overall_band': att.overall_band,
                    'cefr_level': att.cefr_level or '',
                })

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

        except Exception as e:
            _logger.exception('get_pending failed')
            return _error_response(str(e), 500)

    # ------------------------------------------------------------------
    # POST /api/scores/<int:attempt_id>/release
    # ------------------------------------------------------------------
    @http.route('/api/scores/<int:attempt_id>/release', type='http', auth='none',
                methods=['POST'], csrf=False)
    @jwt_required
    def release(self, attempt_id, **kw):
        try:
            Attempt = request.env['encoach.student.attempt'].sudo()
            attempt = Attempt.browse(attempt_id)
            if not attempt.exists():
                return _error_response('Attempt not found', 404)
            if attempt.status != 'pending_approval':
                return _error_response('Attempt is not pending approval', 400)

            user = request.env.user.sudo()
            if attempt.entity_id and user.entity_ids:
                if attempt.entity_id.id not in user.entity_ids.ids:
                    return _error_response('You are not an admin for this entity', 403)

            from odoo.fields import Datetime as DT
            attempt.write({
                'status': 'released',
                'released_at': DT.now(),
                'released_by': user.id,
            })

            return _json_response({'released': True})

        except Exception as e:
            _logger.exception('release failed')
            return _error_response(str(e), 500)

    # ------------------------------------------------------------------
    # POST /api/scores/<int:attempt_id>/reject
    # ------------------------------------------------------------------
    @http.route('/api/scores/<int:attempt_id>/reject', type='http', auth='none',
                methods=['POST'], csrf=False)
    @jwt_required
    def reject(self, attempt_id, **kw):
        try:
            body = _get_json_body()
            Attempt = request.env['encoach.student.attempt'].sudo()
            attempt = Attempt.browse(attempt_id)
            if not attempt.exists():
                return _error_response('Attempt not found', 404)
            if attempt.status not in ('pending_approval', 'scored'):
                return _error_response('Attempt cannot be rejected', 400)

            rejection_note = body.get('rejection_note', '')

            Feedback = request.env['encoach.feedback'].sudo()
            Feedback.create({
                'attempt_id': attempt.id,
                'feedback_text': f"Score rejected: {rejection_note}" if rejection_note
                                 else "Scores rejected and sent back for re-grading.",
                'source': 'teacher',
                'graded_by': request.env.user.id,
            })

            attempt.write({'status': 'scoring'})

            return _json_response({'rejected': True})

        except Exception as e:
            _logger.exception('reject failed')
            return _error_response(str(e), 500)
