File size: 10,754 Bytes
532e19f
 
 
 
 
 
 
 
1b18136
532e19f
 
 
2acac46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88c8f94
2acac46
 
 
1b18136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da114c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b18136
da114c3
 
2acac46
 
 
 
 
88c8f94
 
2acac46
 
 
 
532e19f
f17650a
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
 
 
 
2acac46
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2acac46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532e19f
 
 
 
 
 
2acac46
532e19f
2acac46
532e19f
 
 
 
 
 
 
 
 
1514fe9
ac423d6
1514fe9
 
 
532e19f
 
 
 
2acac46
 
 
 
88c8f94
532e19f
 
 
 
2acac46
532e19f
2acac46
532e19f
 
 
 
2acac46
 
 
532e19f
88c8f94
532e19f
 
f17650a
 
532e19f
 
 
 
 
 
 
 
1b18136
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2acac46
532e19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
google_sheets_logger.py โ€” Optional Google Sheets integration for submission logging

This module provides automatic logging of student submissions to Google Sheets.
If not configured (no GOOGLE_SHEET_ID), it silently fails and the system continues normally.
"""

import os
import json
from datetime import datetime
from typing import Optional

from dotenv import load_dotenv


load_dotenv()


SUMMARY_HEADERS = [
    "ืชืืจื™ืš ื•ืฉืขื”",
    "ืฉื ืกื˜ื•ื“ื ื˜",
    "ืืชื’ืจ",
    "GitHub Repository",
    "ืงื•ื‘ืฅ ื™ืขื“",
    "ืฆื™ื•ืŸ",
    "ื”ื™ื ื˜ื™ื",
    "ื˜ืกื˜ื™ื ืฉืขื‘ืจื•",
    "ื”ืฆืœื™ื—?",
    "ืกื•ื’ ืชื•ืฆืื”",
    "ื ื’ืขื” ื‘ืคื•ื ืงืฆื™ื™ืช ื‘ืื’?",
    "ืชื™ืื•ืจ ื”ื‘ืื’",
    "ื”ืชื›ืชื‘ื•ืช ืขื ื”ืฆ'ืื˜",
    "Hugging Face username",
]


def _service_account_identity(service_account_json: str) -> str:
    if not service_account_json:
        return ""
    try:
        info = json.loads(service_account_json)
    except Exception:
        return ""
    return info.get("client_email", "")


def _format_google_sheets_error(exc: Exception, sheet_id: str, service_account_json: str) -> str:
    service_account_email = _service_account_identity(service_account_json)
    spreadsheet_hint = (
        f"Spreadsheet {sheet_id} was not found or is not shared with {service_account_email}."
        if service_account_email
        else f"Spreadsheet {sheet_id} was not found."
    )

    try:
        import gspread

        if isinstance(exc, gspread.exceptions.SpreadsheetNotFound):
            return spreadsheet_hint
        if isinstance(exc, gspread.exceptions.APIError):
            response = exc.response
            status_code = getattr(response, "status_code", "unknown")
            detail = ""
            try:
                payload = response.json()
                detail = payload.get("error", {}).get("message", "")
            except Exception:
                detail = getattr(response, "text", "") or str(exc)
            if status_code == 404:
                return f"HTTP 404 from Google Sheets API. {spreadsheet_hint} Details: {detail}".strip()
            return f"Google Sheets API error {status_code}: {detail or exc}"
    except Exception:
        pass

    return f"{type(exc).__name__}: {exc}"


def diagnose_google_sheets() -> dict:
    sheet_id = os.getenv("GOOGLE_SHEET_ID", "").strip()
    service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip()
    service_account_file = "google-service-account.json"

    if not sheet_id:
        return {"ok": False, "reason": "Missing GOOGLE_SHEET_ID"}
    if not service_account_json and not os.path.exists(service_account_file):
        return {"ok": False, "reason": "Missing GOOGLE_SERVICE_ACCOUNT_JSON and google-service-account.json"}

    try:
        import gspread
        from google.oauth2.service_account import Credentials

        scopes = [
            'https://www.googleapis.com/auth/spreadsheets',
            'https://www.googleapis.com/auth/drive'
        ]
        if service_account_json:
            service_account_info = json.loads(service_account_json)
            creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
        else:
            creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)

        client = gspread.authorize(creds)
        client.open_by_key(sheet_id).sheet1
        return {"ok": True, "reason": ""}
    except Exception as exc:
        return {"ok": False, "reason": _format_google_sheets_error(exc, sheet_id, service_account_json)}


def _ensure_sheet_headers(sheet) -> None:
    current_headers = sheet.row_values(1)
    if current_headers[:len(SUMMARY_HEADERS)] == SUMMARY_HEADERS:
        return

    sheet.update(range_name="A1:N1", values=[SUMMARY_HEADERS])
    sheet.format("A1:N1", {
        "textFormat": {"bold": True},
        "backgroundColor": {"red": 0.9, "green": 0.9, "blue": 0.9},
    })


def _write_next_row(sheet, row: list) -> None:
    next_row = len(sheet.col_values(1)) + 1
    end_column = chr(ord("A") + len(row) - 1)
    sheet.update(
        range_name=f"A{next_row}:{end_column}{next_row}",
        values=[row],
    )


def log_to_google_sheets(
    student_name: str,
    repo_url: str,
    hints_used: int,
    score: int,
    total_tests: int,
    passed_tests: int,
    all_passed: bool,
    chat_history: list,
    submission_record: Optional[dict] = None,
) -> bool:
    """
    Log submission to Google Sheets.
    
    Returns True if successful, False otherwise.
    If Google Sheets is not configured, returns False silently.
    """
    
    # Check if Google Sheets is configured
    sheet_id = os.getenv("GOOGLE_SHEET_ID")
    if not sheet_id:
        return False  # Silently skip if not configured
    
    try:
        import gspread
        from google.oauth2.service_account import Credentials
        
        # Try to get service account from environment variable first (for cloud deployment)
        service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")
        
        if service_account_json:
            # Parse JSON from environment variable
            service_account_info = json.loads(service_account_json)
            scopes = [
                'https://www.googleapis.com/auth/spreadsheets',
                'https://www.googleapis.com/auth/drive'
            ]
            creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)
        else:
            # Fall back to file (for local development)
            service_account_file = "google-service-account.json"
            if not os.path.exists(service_account_file):
                print("โš ๏ธ Google Sheets: service account not configured (neither env var nor file)")
                return False
            
            scopes = [
                'https://www.googleapis.com/auth/spreadsheets',
                'https://www.googleapis.com/auth/drive'
            ]
            creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)
        
        client = gspread.authorize(creds)
        
        # Open the sheet
        sheet = client.open_by_key(sheet_id).sheet1
        
        # Initialize or migrate headers to the current schema.
        try:
            _ensure_sheet_headers(sheet)
        except Exception as e:
            print(f"โš ๏ธ Could not set headers: {e}")
        
        # Prepare row data
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # Format chat history nicely
        if chat_history:
            chat_text = "\n\n".join([
                (
                    f"{'ื”ื™ื ื˜' if msg.get('gave_hint') is True else 'ืฉื™ื—ื”'} #{i+1}:\n"
                    f"ืฉืืœื”: {msg.get('question') or msg.get('summary', 'N/A')}\n"
                    f"ืชืฉื•ื‘ื”: {msg.get('response', 'N/A')}"
                )
                for i, msg in enumerate(chat_history)
            ])
        else:
            chat_text = "ืœื ื”ืฉืชืžืฉ ื‘ื”ื™ื ื˜ื™ื"

        challenge = submission_record.get("challenge", {}) if submission_record else {}
        scoring = submission_record.get("scoring", {}) if submission_record else {}
        submission = submission_record.get("submission", {}) if submission_record else {}
        student = submission_record.get("student", {}) if submission_record else {}
        
        row = [
            timestamp,
            student_name or "Anonymous",
            challenge.get("challenge_id", ""),
            repo_url,
            challenge.get("target_file", ""),
            score,
            hints_used,
            f"{passed_tests}/{total_tests}",
            "โœ… ื”ืฆืœื™ื—" if all_passed else "โŒ ืœื ื”ืฆืœื™ื—",
            scoring.get("submission_outcome", ""),
            "ื›ืŸ" if submission.get("touched_bug_function") else "ืœื",
            challenge.get("bug_description", ""),
            chat_text,
            student.get("provider_user_id", ""),
        ]
        
        # Write deterministically to the next free row.
        _write_next_row(sheet, row)
        
        print(f"โœ… Logged to Google Sheets: {student_name} - Score: {score}")
        return True
        
    except ImportError:
        print("โš ๏ธ Google Sheets: gspread not installed (pip install gspread google-auth)")
        return False
    except Exception as e:
        print(f"โš ๏ธ Google Sheets logging failed: {_format_google_sheets_error(e, sheet_id, service_account_json or '')}")
        return False


def initialize_sheet_headers(sheet_id: Optional[str] = None) -> bool:
    """
    Initialize Google Sheet with headers if it's empty.
    Call this once to set up the sheet.
    """
    
    sheet_id = sheet_id or os.getenv("GOOGLE_SHEET_ID")
    if not sheet_id:
        print("โŒ GOOGLE_SHEET_ID not set")
        return False
    
    try:
        import gspread
        from google.oauth2.service_account import Credentials
        
        service_account_file = "google-service-account.json"
        if not os.path.exists(service_account_file):
            print(f"โŒ Service account file not found: {service_account_file}")
            return False
        
        scopes = [
            'https://www.googleapis.com/auth/spreadsheets',
            'https://www.googleapis.com/auth/drive'
        ]
        creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)
        client = gspread.authorize(creds)
        
        sheet = client.open_by_key(sheet_id).sheet1
        
        _ensure_sheet_headers(sheet)
        print("โœ… Headers initialized!")
        return True
        
    except Exception as e:
        print(f"โŒ Failed to initialize headers: {e}")
        return False


# CLI tool for testing
if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == "init":
        # Initialize headers
        sheet_id = os.getenv("GOOGLE_SHEET_ID")
        if not sheet_id:
            print("Set GOOGLE_SHEET_ID in .env first!")
            sys.exit(1)
        
        success = initialize_sheet_headers(sheet_id)
        sys.exit(0 if success else 1)
    
    else:
        # Test logging
        print("Testing Google Sheets logging...")
        success = log_to_google_sheets(
            student_name="Test Student",
            repo_url="https://github.com/test/repo",
            hints_used=2,
            score=85,
            total_tests=10,
            passed_tests=8,
            all_passed=False,
            chat_history=[{"role": "user", "content": "test"}],
        )
        
        if success:
            print("โœ… Test successful!")
        else:
            print("โŒ Test failed - check configuration")