"""
Free diagnostic mini-quiz (Part 8 ASAP) — no login required.
"""
from __future__ import annotations

import random
from decimal import Decimal

from django.db import transaction

from apps.courses.exam_generation import InsufficientQuestionBank, eligible_questions_qs
from apps.courses.models import DIAGNOSTIC_QUESTION_COUNT, Course, DiagnosticAttempt


def select_diagnostic_questions(course: Course, count: int | None = None):
    count = count or DIAGNOSTIC_QUESTION_COUNT
    pool = list(eligible_questions_qs(course))
    if len(pool) < count:
        raise InsufficientQuestionBank(
            f'Need {count} verified questions for the free diagnostic; bank has {len(pool)}.'
        )
    random.shuffle(pool)
    return pool[:count]


@transaction.atomic
def save_diagnostic_attempt(
    *,
    course: Course,
    email: str,
    whatsapp: str,
    answers: dict[int, str],
    questions,
) -> DiagnosticAttempt:
    """
    answers: {question_id: 'A'|'B'|'C'|'D'} using bank correct_option letters
    (diagnostic does not shuffle options for simplicity).
    """
    correct = 0
    qids = []
    for q in questions:
        qids.append(q.pk)
        selected = (answers.get(q.pk) or answers.get(str(q.pk)) or '').strip().upper()
        if selected and selected == q.correct_option:
            correct += 1
    total = len(questions)
    percent = Decimal('0.00') if total == 0 else (
        Decimal(correct * 100) / Decimal(total)
    ).quantize(Decimal('0.01'))

    return DiagnosticAttempt.objects.create(
        course=course,
        email=email.strip().lower(),
        whatsapp=(whatsapp or '').strip()[:30],
        score=percent,
        correct_count=correct,
        total_asked=total,
        question_ids=qids,
    )


def freelancer_share_blurb(certificate, verify_absolute_url: str) -> str:
    """One-liner ready for Fiverr / Upwork profiles."""
    return (
        f"Certified in {certificate.course_title_snapshot} "
        f"({certificate.assessment_label}) — {certificate.score_band_label}. "
        f"Verify: {verify_absolute_url}"
    )
