import random
from exams.models import ModelQuestion
from game.models import StudentMonster, Battle

def start_battle(student, monster_id):
    monster = StudentMonster.objects.get(id=monster_id, student=student)
    questions = ModelQuestion.objects.filter(kc=monster.kc)
    if not questions.exists():
        questions = ModelQuestion.objects.all()
    if not questions.exists():
        return None
    q = random.choice(questions)
    battle = Battle.objects.create(student=student, monster=monster, wild_kc=monster.kc)
    return {
        'battle_id': battle.id,
        'monster_name': monster.name,
        'monster_hp': monster.current_hp,
        'max_hp': monster.max_hp,
        'question_text': q.question_text,
    }

def process_attack(battle_id, student_answer):
    battle = Battle.objects.get(id=battle_id)
    monster = battle.monster
    q = ModelQuestion.objects.filter(kc=battle.wild_kc).first() or ModelQuestion.objects.first()
    correct = q.model_answer.strip().lower() in student_answer.strip().lower() if q and q.model_answer else False
    if correct:
        damage = random.randint(15, 25)
        monster.xp += 20
        monster.current_hp = min(monster.max_hp, monster.current_hp + 10)
        battle.is_won = True
        msg = f"Shabash! Sahi jawab. Aap ke monster ne {damage} damage kiya aur 10 HP heal kiye."
    else:
        damage = random.randint(10, 20)
        monster.current_hp = max(0, monster.current_hp - damage)
        battle.is_won = False
        msg = f"Ghalat jawab. Aap ke monster ko {damage} damage laga."
    if monster.xp >= (monster.level * 100):
        monster.level += 1
        monster.xp = 0
        monster.max_hp += 20
        monster.current_hp = monster.max_hp
        msg += f" Level Up! Aap ka monster ab Level {monster.level} par hai."
    monster.save()
    battle.save()
    return {'success': correct, 'message': msg, 'monster_hp': monster.current_hp, 'max_hp': monster.max_hp, 'level': monster.level}
