"""Store complete challenge submissions in Supabase using its REST API.""" from __future__ import annotations import json import os from typing import Any from urllib.error import HTTPError, URLError from urllib.parse import urlencode, urlsplit from urllib.request import Request, urlopen TABLE_NAME = "submissions" def _configuration() -> tuple[str, str] | tuple[None, str]: url = os.getenv("SUPABASE_URL", "").strip().rstrip("/") key = ( os.getenv("SUPABASE_SECRET_KEY", "").strip() or os.getenv("SUPABASE_SERVICE_ROLE_KEY", "").strip() ) if not url or not key: return None, "Missing SUPABASE_URL or Supabase server secret" if urlsplit(url).scheme != "https": return None, "SUPABASE_URL must use HTTPS" return (url, key), "" def _headers(key: str, *, prefer: str = "return=minimal") -> dict[str, str]: headers = { "apikey": key, "Content-Type": "application/json", "Accept": "application/json", "Prefer": prefer, } # Legacy service_role keys are JWTs. New sb_secret keys are not bearer tokens. if key.startswith("eyJ"): headers["Authorization"] = f"Bearer {key}" return headers def _report_value(value: Any) -> str: return str(value).strip() if value not in (None, "") else "(not provided)" def _report_section(title: str, value: Any) -> str: return f"{title}\n{'=' * len(title)}\n{_report_value(value)}" def _build_review_report(record: dict[str, Any]) -> str: student = record.get("student") or {} challenge = record.get("challenge") or {} submission = record.get("submission") or {} tests = record.get("tests") or {} scoring = record.get("scoring") or {} per_test_before = {item.get("num"): item.get("status") for item in tests.get("per_test_before", [])} per_test_after = {item.get("num"): item.get("status") for item in tests.get("per_test_after", [])} test_numbers = sorted(set(per_test_before) | set(per_test_after)) lines = [ f"SUBMISSION REVIEW: {record.get('submission_id', '(unknown)')}", "=" * 72, f"Student: {_report_value(student.get('name'))}", f"Hugging Face: {_report_value(student.get('provider_user_id'))}", f"Submitted: {_report_value(record.get('timestamp'))}", f"Challenge: {_report_value(challenge.get('challenge_id'))}", f"Repository: {_report_value(challenge.get('repo_url'))}", f"Target file: {_report_value(challenge.get('target_file'))}", f"Attempt: {_report_value(submission.get('attempt_number'))}", "", _report_section("WHAT WAS THE BUG?", challenge.get("bug_description")), _report_section("CHALLENGE SUMMARY", challenge.get("challenge_summary")), _report_section("BUGGY CODE GIVEN TO THE STUDENT", challenge.get("buggy_code")), _report_section("STUDENT'S CHANGES (DIFF)", submission.get("student_diff")), _report_section("EXPECTED FIX", challenge.get("expected_fixed_code")), "TEST RESULTS (before -> after)", "==============================", f"Before: {tests.get('before_passed', 0)}/{tests.get('before_total', 0)} passed", f"After: {tests.get('passed_tests', 0)}/{tests.get('total_tests', 0)} passed", ] for number in test_numbers: lines.append( f"Test {number}: {per_test_before.get(number, '-')} -> {per_test_after.get(number, '-')}" ) lines.extend([ "", f"LLM score: {_report_value(scoring.get('llm_score'))}", f"Hint penalty: {_report_value(scoring.get('hint_penalty'))}", f"Final score: {_report_value(scoring.get('total_score'))}", f"Outcome: {_report_value(scoring.get('submission_outcome'))}", _report_section("SCORING EXPLANATION", scoring.get("llm_explanation")), _report_section("FULL TEST OUTPUT", tests.get("test_output")), "CHAT HISTORY", "============", ]) chat_history = submission.get("chat_history") or [] if not chat_history: lines.append("No chat history recorded.") else: for index, item in enumerate(chat_history, 1): label = "HINT" if item.get("gave_hint") else "CHAT" lines.extend([ f"[{index}] {label}", f"Student: {_report_value(item.get('question'))}", f"Assistant: {_report_value(item.get('response'))}", "", ]) return "\n".join(lines) def _submission_row(record: dict[str, Any]) -> dict[str, Any]: student = record.get("student") or {} challenge = record.get("challenge") or {} submission = record.get("submission") or {} tests = record.get("tests") or {} scoring = record.get("scoring") or {} payload = dict(record) payload["cloud"] = dict(record.get("cloud") or {}) payload["cloud"]["supabase"] = {"status": "success", "error": ""} return { "submission_id": str(record.get("submission_id") or ""), "submitted_at": record.get("timestamp"), "student_name": student.get("name") or "Anonymous", "auth_provider": student.get("auth_provider") or None, "provider_user_id": student.get("provider_user_id") or None, "challenge_id": challenge.get("challenge_id") or None, "repo_url": challenge.get("repo_url") or None, "target_file": challenge.get("target_file") or None, "attempt_number": submission.get("attempt_number", 1), "hints_used": submission.get("hints_used", 0), "llm_score": scoring.get("llm_score"), "total_score": scoring.get("total_score"), "passed_tests": tests.get("passed_tests"), "total_tests": tests.get("total_tests"), "submission_outcome": scoring.get("submission_outcome") or None, "review_report": _build_review_report(record), "payload": payload, } def upload_submission_to_supabase(record: dict[str, Any]) -> tuple[bool, str]: """Upsert a submission; returns success and a safe, non-secret diagnostic.""" configured, reason = _configuration() if configured is None: return False, reason if not isinstance(record, dict) or not record.get("submission_id"): return False, "Submission record is missing submission_id" url, key = configured query = urlencode({"on_conflict": "submission_id"}) request = Request( f"{url}/rest/v1/{TABLE_NAME}?{query}", data=json.dumps(_submission_row(record), ensure_ascii=False).encode("utf-8"), headers=_headers(key, prefer="resolution=merge-duplicates,return=minimal"), method="POST", ) try: with urlopen(request, timeout=12): return True, "" except HTTPError as exc: exc.close() if exc.code in (401, 403): return False, "Supabase rejected the server key or table privileges (HTTP 401/403)" if exc.code == 404: return False, "Supabase table or REST endpoint not found (HTTP 404)" if exc.code == 413: return False, "Submission is too large for the Supabase API (HTTP 413)" return False, f"Supabase returned HTTP {exc.code}" except (TimeoutError, URLError, OSError) as exc: return False, f"Supabase connection failed: {type(exc).__name__}" except (TypeError, ValueError) as exc: return False, f"Submission JSON could not be encoded: {type(exc).__name__}" def diagnose_supabase() -> dict[str, Any]: """Check server configuration and table access without returning any key.""" configured, reason = _configuration() if configured is None: return {"ok": False, "reason": reason} url, key = configured query = urlencode({"select": "submission_id", "limit": "1"}) request = Request( f"{url}/rest/v1/{TABLE_NAME}?{query}", headers=_headers(key), method="GET", ) try: with urlopen(request, timeout=8): return {"ok": True, "reason": ""} except HTTPError as exc: exc.close() if exc.code in (401, 403): reason = "Supabase rejected the server key or table privileges (HTTP 401/403)" elif exc.code == 404: reason = "Supabase table or REST endpoint not found (HTTP 404)" else: reason = f"Supabase returned HTTP {exc.code}" return {"ok": False, "reason": reason} except (TimeoutError, URLError, OSError) as exc: return {"ok": False, "reason": f"Supabase connection failed: {type(exc).__name__}"}