import requests
import io
from PIL import Image

CONVEX_SUBMIT_URL = 'https://astute-rat-865.convex.site/submit'

def submit(id_student, name, assignment_name, result, batch, question_name='', code=''):
    data = {
        "studentId": id_student,
        "studentName": name,
        "assignmentName": assignment_name,
        "questionName": question_name,
        "batch": batch,
        "code": code,
        "result": str(result)
    }

    try:
        r = requests.post(CONVEX_SUBMIT_URL, json=data)
        if r.status_code == 200:
            try:
                response_data = r.json()
                if 'score' in response_data and response_data['score'] is not None:
                    return f'Assignment successfully submitted. Score: {response_data["score"]}'
            except:
                pass
            return 'Assignment successfully submitted'
        else:
            return f'Failed to submit assignment: {r.text}'
    except Exception as e:
        return f'Error submitting assignment: {str(e)}'

def submit_image(id_student, name, assignment_name, question_name, batch, image_path):
    try:
        # Prepare data fields
        data = {
            "studentId": id_student,
            "studentName": name,
            "assignmentName": assignment_name,
            "questionName": question_name,
            "batch": batch,
        }

        # Prepare image file
        # We open the image to ensure it's valid and maybe resize/convert if needed in future
        # For now just re-saving to bytes to ensure clean upload
        image = Image.open(image_path).convert('RGB')
        image_byte_arr = io.BytesIO()
        image.save(image_byte_arr, format='JPEG')
        image_byte_arr.seek(0)

        files = {
            'image': ('submission.jpg', image_byte_arr, 'image/jpeg')
        }

        r = requests.post(CONVEX_SUBMIT_URL, data=data, files=files)
        
        if r.status_code == 200:
            try:
                response_data = r.json()
                if 'score' in response_data and response_data['score'] is not None:
                    return f'Assignment successfully submitted. Score: {response_data["score"]}'
            except:
                pass
            return 'Assignment successfully submitted'
        else:
            return f'Failed to submit assignment: {r.text}'
            
    except Exception as e:
        return f'Error submitting assignment: {str(e)}'