Repository navigation
Expand file tree
/
Copy pathsolution.html
More file actions
578 lines (516 loc) · 31.3 KB
/
Copy pathsolution.html
File metadata and controls
578 lines (516 loc) · 31.3 KB
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Viewer - CP Archive</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
<link id="prism-theme" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css">
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js"></script>
<link rel="stylesheet" href="assets/app.css">
<script src="assets/app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.3.0/marked.min.js"></script>
</head>
<body>
<div class="page-shell">
<header class="site-header">
<div class="container header-inner">
<button class="brand brand-button" type="button" onclick="window.history.back()" aria-label="Back to previous page">
<span class="brand-mark" aria-hidden="true">
<svg width="25" height="25" viewBox="0 0 24 24" fill="none">
<path d="M19 12H5M11 6l-6 6 6 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</span>
<span class="brand-copy">
<span class="brand-title" id="header-title">Loading solution</span>
<span class="brand-subtitle">Code viewer</span>
</span>
</button>
<div class="header-actions">
<a class="text-button hide-mobile" href="index.html">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M3 10.5 12 3l9 7.5V21h-6v-6H9v6H3V10.5Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
</svg>
Home
</a>
<button class="icon-button theme-toggle" type="button" data-theme-toggle aria-label="Toggle light and dark mode">
<svg class="sun-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M12 3v2M12 19v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M3 12h2M19 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42M16.5 12a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Z" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
<svg class="moon-icon" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M21 14.5A8.5 8.5 0 0 1 9.5 3 7 7 0 1 0 21 14.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
</div>
</div>
</header>
<main class="page-main">
<div class="container">
<section class="page-heading">
<div>
<p class="eyebrow">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M16 18 22 12 16 6M8 6 2 12l6 6M14 4l-4 16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
Source archive
</p>
<h1 class="compact-title" id="problem-title">Loading problem</h1>
</div>
<div class="toolbar" id="solution-toolbar" style="display: flex; gap: 10px; align-items: center;">
<button class="text-button ai-insights-btn" id="ai-insights-trigger-btn" type="button" onclick="handleInsightsTrigger()">
<svg class="ai-sparkle-icon" viewBox="0 0 24 24" fill="none" style="width:16px; height:16px; stroke:#a855f7; stroke-width:2;">
<path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<span id="ai-btn-text">Generate AI Insights</span>
</button>
<button class="text-button toggle-sidebar-btn" type="button" aria-label="Toggle notes sidebar">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true" style="stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; width: 16px; height: 16px;">
<path d="M15 19l-7-7 7-7"/>
</svg>
Toggle Notes
</button>
</div>
</section>
<section class="solution-layout">
<aside class="solution-card">
<div class="card-header">
<h2 class="card-title">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M12 17h.01M12 13a3 3 0 1 0-3-3M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
Problem notes
</h2>
</div>
<div id="readme-content" class="problem-info markdown-body custom-scrollbar">
<div class="loading-state">Loading README...</div>
</div>
</aside>
<section class="solution-card code-window">
<div class="card-header">
<div class="window-dots" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</div>
<span class="filename" id="filename-display">solution.cpp</span>
<button class="text-button" type="button" onclick="copyCode()" aria-label="Copy solution code">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="M8 8V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2M6 8h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
</svg>
<span id="copy-label">Copy</span>
</button>
</div>
<div class="code-body custom-scrollbar">
<pre><code id="code-content" class="language-cpp">Loading solution...</code></pre>
</div>
</section>
</section>
<!-- AI Code Insights Card -->
<section class="solution-card ai-insights-card" id="ai-insights-container" style="display: none; margin-top: 24px;">
<div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
<div style="display: flex; align-items: center; gap: 8px;">
<svg style="width: 20px; height: 20px; color: #a855f7;" viewBox="0 0 24 24" fill="none">
<path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<h2 class="card-title" style="margin: 0;">AI Code Insights & Quality Breakdown</h2>
<span class="badge" id="ai-model-badge" style="background: rgba(168, 85, 247, 0.2); color: #c084fc; border: 1px solid rgba(168, 85, 247, 0.4); padding: 2px 8px; border-radius: 12px; font-size: 11px;">gemini-3.5-flash-lite</span>
</div>
<button class="text-button" onclick="handleInsightsTrigger(true)" style="font-size: 12px; gap: 4px;" title="Regenerate AI Insights">
<svg viewBox="0 0 24 24" fill="none" style="width: 14px; height: 14px; stroke: currentColor; stroke-width: 2;">
<path d="M23 4v6h-6M1 20v-6h6M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
</svg>
Regenerate
</button>
</div>
<div class="insights-body custom-scrollbar" style="padding: 20px; display: grid; gap: 20px;">
<!-- Approach & Tags -->
<div>
<div id="ai-tags-container" style="display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 12px;"></div>
<h3 id="ai-title" style="font-size: 18px; font-weight: 700; color: var(--text-primary); margin-bottom: 8px;"></h3>
<p id="ai-approach" style="color: var(--text-secondary); line-height: 1.6; font-size: 14px;"></p>
</div>
<!-- Grid for Complexity & Score -->
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px;">
<!-- Complexity Card -->
<div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 16px;">
<h4 style="color: #60a5fa; margin-bottom: 10px; font-size: 14px; font-weight: 600;">⚡ Complexity Analysis</h4>
<div style="margin-bottom: 8px; font-size: 13px;">
<strong>Time Complexity:</strong> <span id="ai-time-comp" style="font-family: monospace; color: #34d399;"></span>
<p id="ai-time-just" style="font-size: 12px; color: var(--text-muted); margin-top: 4px;"></p>
</div>
<div style="font-size: 13px;">
<strong>Space Complexity:</strong> <span id="ai-space-comp" style="font-family: monospace; color: #34d399;"></span>
<p id="ai-space-just" style="font-size: 12px; color: var(--text-muted); margin-top: 4px;"></p>
</div>
</div>
<!-- Quality Score Card -->
<div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 16px; display: flex; align-items: center; gap: 16px;">
<div style="width: 64px; height: 64px; border-radius: 50%; border: 3px solid #a855f7; display: flex; align-items: center; justify-content: center; flex-direction: column; flex-shrink: 0;">
<span id="ai-quality-score" style="font-size: 20px; font-weight: 800; color: #a855f7;">--</span>
<span style="font-size: 9px; text-transform: uppercase; color: var(--text-muted);">Score</span>
</div>
<div>
<h4 id="ai-quality-label" style="color: var(--text-primary); font-size: 15px; font-weight: 700; margin: 0;">Evaluating...</h4>
<p style="font-size: 12px; color: var(--text-muted); margin-top: 4px;">Evaluated against competitive programming clean code & edge case standards.</p>
</div>
</div>
</div>
<!-- Step-by-Step Walkthrough -->
<div>
<h4 style="color: var(--text-primary); margin-bottom: 10px; font-size: 15px;">🔍 Step-by-Step Code Walkthrough</h4>
<div id="ai-code-breakdown" style="display: grid; gap: 10px;"></div>
</div>
<!-- Optimizations & Alternatives -->
<div>
<h4 style="color: var(--text-primary); margin-bottom: 10px; font-size: 15px;">💡 Optimization & Alternative Approaches</h4>
<div id="ai-alternatives" style="display: grid; gap: 10px;"></div>
</div>
</div>
</section>
</div>
</main>
<footer class="site-footer">
<div class="container footer-inner">
<span><strong>CP Submission Archive</strong> solution view.</span>
<span data-theme-label>Theme</span>
</div>
</footer>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-c.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-cpp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script>
const GITHUB_USERNAME = "LIGHTUNCHARGED";
const REPO_NAME = "Competitive-Programming";
const BRANCH = "main";
let rawCode = "";
async function fetchFirst(urls) {
let lastError;
for (const url of urls) {
try {
const response = await fetch(url);
if (response.ok) return response;
lastError = new Error(`${response.status} ${response.statusText}`);
} catch (error) {
lastError = error;
}
}
throw lastError || new Error("No sources available.");
}
document.addEventListener("DOMContentLoaded", async () => {
const urlParams = new URLSearchParams(window.location.search);
const folderPath = urlParams.get("path");
const codeEl = document.getElementById("code-content");
const readmeEl = document.getElementById("readme-content");
const titleEl = document.getElementById("problem-title");
const headerTitleEl = document.getElementById("header-title");
const { escapeHtml, formatProblemName, encodePath } = window.CPArchive;
// Collapsible sidebar logic
const toggleBtn = document.querySelector(".toggle-sidebar-btn");
const layout = document.querySelector(".solution-layout");
if (toggleBtn && layout) {
toggleBtn.addEventListener("click", () => {
layout.classList.toggle("sidebar-collapsed");
const aside = layout.querySelector("aside");
if (layout.classList.contains("sidebar-collapsed")) {
aside.style.display = "none";
layout.style.gridTemplateColumns = "minmax(0, 1fr)";
} else {
aside.style.display = "block";
layout.style.gridTemplateColumns = "minmax(280px, 0.74fr) minmax(0, 1.26fr)";
}
});
}
// Sync Prism style with root site theme
const observer = new MutationObserver(() => updatePrismTheme());
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
function updatePrismTheme() {
const theme = document.documentElement.dataset.theme || "light";
const prismThemeLink = document.getElementById("prism-theme");
if (prismThemeLink) {
if (theme === "dark") {
prismThemeLink.href = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css";
} else {
prismThemeLink.href = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css";
}
}
}
updatePrismTheme();
if (!folderPath) {
titleEl.textContent = "Missing problem path";
headerTitleEl.textContent = "Missing path";
codeEl.textContent = "// Error: No problem path provided in the URL.";
readmeEl.innerHTML = `<div class="error-state">No problem path was provided.</div>`;
return;
}
const folderName = formatProblemName(folderPath.split("/").pop());
const encodedPath = encodePath(folderPath);
const rawBaseUrl = `https://raw.githubusercontent.com/${GITHUB_USERNAME}/${REPO_NAME}/${BRANCH}/${encodedPath}`;
titleEl.textContent = folderName;
headerTitleEl.textContent = folderName;
try {
const readmeRes = await fetchFirst([
`${encodedPath}/README.md`,
`${rawBaseUrl}/README.md`
]);
const markdown = await readmeRes.text();
readmeEl.innerHTML = window.marked ? marked.parse(markdown) : `<pre>${escapeHtml(markdown)}</pre>`;
} catch (error) {
console.error("Failed to fetch README", error);
readmeEl.innerHTML = `<p class="muted">No README.md was found for this problem.</p>`;
}
try {
const candidates = [
{ filename: "solution.cpp", lang: "cpp" },
{ filename: "solution.py", lang: "python" },
{ filename: "solution.c", lang: "c" }
];
let loaded = null;
for (const candidate of candidates) {
try {
const response = await fetchFirst([
`${encodedPath}/${candidate.filename}`,
`${rawBaseUrl}/${candidate.filename}`
]);
loaded = { ...candidate, source: await response.text() };
break;
} catch (error) {
loaded = null;
}
}
if (!loaded) {
codeEl.textContent = "// Error: Could not find solution.cpp, solution.py, or solution.c in this folder.";
return;
}
rawCode = loaded.source;
codeEl.className = `language-${loaded.lang}`;
codeEl.textContent = rawCode;
document.getElementById("filename-display").textContent = loaded.filename;
if (window.Prism) Prism.highlightElement(codeEl);
} catch (error) {
console.error("Failed to fetch code", error);
codeEl.textContent = "// Error: Failed to load the solution source.";
}
// Fetch AI Code Insights if available
fetchAIInsights(encodedPath, rawBaseUrl);
});
async function fetchAIInsights(encodedPath, rawBaseUrl) {
try {
const response = await fetchFirst([
`${encodedPath}/insights.json`,
`${rawBaseUrl}/insights.json`
]);
const data = await response.json();
renderAIInsights(data);
const btnText = document.getElementById("ai-btn-text");
if (btnText) btnText.textContent = "AI Insights Loaded";
} catch (error) {
console.log("No AI insights found for this problem.");
}
}
function formatLatex(text) {
if (!text) return "";
if (window.katex) {
// Replace inline $...$ or $$...$$ with rendered KaTeX html
return text.replace(/\$\$([\s\S]+?)\$\$/g, (match, math) => {
try { return katex.renderToString(math, { displayMode: true }); } catch(e) { return match; }
}).replace(/\$([^\$\n]+?)\$/g, (match, math) => {
try { return katex.renderToString(math, { displayMode: false }); } catch(e) { return match; }
});
}
return text;
}
function renderAIInsights(data) {
const container = document.getElementById("ai-insights-container");
if (!container) return;
container.style.display = "block";
if (data.model) {
document.getElementById("ai-model-badge").textContent = data.model;
}
document.getElementById("ai-title").innerHTML = formatLatex(data.title || "AI Code Insights");
document.getElementById("ai-approach").innerHTML = formatLatex(data.approach_explanation || "");
// Tags
const tagsContainer = document.getElementById("ai-tags-container");
tagsContainer.innerHTML = (data.algorithm_tags || []).map(t =>
`<span style="background: rgba(168, 85, 247, 0.15); color: #c084fc; border: 1px solid rgba(168, 85, 247, 0.3); padding: 2px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">${t}</span>`
).join("");
// Complexities
document.getElementById("ai-time-comp").innerHTML = formatLatex(data.complexity_analysis?.time_complexity || "");
document.getElementById("ai-time-just").innerHTML = formatLatex(data.complexity_analysis?.time_justification || "");
document.getElementById("ai-space-comp").innerHTML = formatLatex(data.complexity_analysis?.space_complexity || "");
document.getElementById("ai-space-just").innerHTML = formatLatex(data.complexity_analysis?.space_justification || "");
// Quality Score
if (data.code_quality) {
document.getElementById("ai-quality-score").textContent = data.code_quality.score || 0;
document.getElementById("ai-quality-label").textContent = data.code_quality.rating_label || "Evaluated";
}
// Breakdown
const breakdownEl = document.getElementById("ai-code-breakdown");
breakdownEl.innerHTML = (data.code_breakdown || []).map(item => `
<div style="background: rgba(255,255,255,0.02); border-left: 3px solid #a855f7; padding: 12px 16px; border-radius: 4px;">
<strong style="color: #e9d5ff; font-size: 14px;">Step ${item.step}: ${item.section_title}</strong>
<p style="font-size: 13px; color: var(--text-secondary); margin-top: 6px; line-height: 1.5;">${formatLatex(item.explanation)}</p>
</div>
`).join("");
// Alternatives
const altEl = document.getElementById("ai-alternatives");
altEl.innerHTML = (data.optimization_and_alternatives || []).map(alt => `
<div style="background: rgba(255,255,255,0.02); border: 1px solid rgba(255,255,255,0.06); padding: 12px 16px; border-radius: 6px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<strong style="color: #60a5fa; font-size: 14px;">${alt.approach_name}</strong>
<span style="font-family: monospace; font-size: 12px; color: #34d399;">${formatLatex(alt.time_complexity)} | ${formatLatex(alt.space_complexity)}</span>
</div>
<p style="font-size: 12px; color: var(--text-muted); line-height: 1.5;">${formatLatex(alt.tradeoffs)}</p>
</div>
`).join("");
if (window.renderMathInElement) {
try {
renderMathInElement(container, {
delimiters: [
{left: '$$', right: '$$', display: true},
{left: '$', right: '$', display: false},
{left: '\\(', right: '\\)', display: false},
{left: '\\[', right: '\\]', display: true}
],
throwOnError: false
});
} catch(e) { console.error("KaTeX render error", e); }
}
}
async function handleInsightsTrigger(force = false) {
const btn = document.getElementById("ai-insights-trigger-btn");
const btnText = document.getElementById("ai-btn-text");
const urlParams = new URLSearchParams(window.location.search);
const folderPath = urlParams.get("path");
if (!folderPath) {
alert("No problem path found in URL.");
return;
}
let pat = localStorage.getItem("GITHUB_PAT");
let geminiKey = localStorage.getItem("GEMINI_API_KEY");
if (!pat && !geminiKey) {
const tokenInput = prompt(
"💡 To generate AI Insights dynamically:\n\n" +
"Option A: Enter a GitHub Personal Access Token (PAT) to trigger the automated GitHub Actions pipeline.\n" +
"Option B: Enter your Gemini API Key to generate insights instantly in your browser.\n\n" +
"Paste your Token or Gemini API Key below:"
);
if (!tokenInput || !tokenInput.trim()) {
return;
}
const cleaned = tokenInput.trim();
if (cleaned.startsWith("ghp_") || cleaned.startsWith("github_pat_")) {
pat = cleaned;
localStorage.setItem("GITHUB_PAT", pat);
} else {
geminiKey = cleaned;
localStorage.setItem("GEMINI_API_KEY", geminiKey);
}
}
btn.disabled = true;
btnText.textContent = "Analyzing solution with Gemini...";
// Strategy 1: If Gemini API Key is stored, generate directly in browser for instant 2s rendering
if (geminiKey) {
try {
const data = await generateInsightsClientSide(folderPath, geminiKey);
renderAIInsights(data);
alert("✨ AI Insights generated instantly in browser!");
return;
} catch (err) {
console.warn("Client-side Gemini generation failed:", err);
alert("Direct Gemini call failed: " + err.message + "\nRetrying via GitHub Actions dispatch...");
}
}
// Strategy 2: Trigger GitHub Repository Dispatch via GitHub PAT
try {
const headers = {
"Accept": "application/vnd.github+json",
"Content-Type": "application/json"
};
if (pat) {
headers["Authorization"] = `Bearer ${pat}`;
}
const response = await fetch("https://api.github.com/repos/LIGHTUNCHARGED/Competitive-Programming/dispatches", {
method: "POST",
headers: headers,
body: JSON.stringify({
event_type: "generate_insight",
client_payload: {
path: folderPath,
force: force
}
})
});
if (response.ok || response.status === 204) {
alert("✨ AI Insights generation pipeline triggered! Gemini is analyzing the code in GitHub Actions and will commit the results shortly.");
} else if (response.status === 401 || response.status === 403) {
localStorage.removeItem("GITHUB_PAT");
alert("Authentication error (HTTP " + response.status + "). Please check your GitHub PAT permissions (must have 'repo' / 'contents:write' scope).");
} else {
alert("GitHub API response: " + response.status + " " + response.statusText);
}
} catch (err) {
alert("Unable to trigger online dispatch: " + err.message);
} finally {
btn.disabled = false;
btnText.textContent = "Generate AI Insights";
}
}
async function generateInsightsClientSide(folderPath, apiKey) {
const readmeEl = document.getElementById("readme-content");
const readmeText = readmeEl ? readmeEl.innerText : "";
const codeText = rawCode || "";
const promptText = `
### PROBLEM STATEMENT
${readmeText}
### SOLUTION CODE
${codeText}
`;
const systemInstruction = `You are a World-Class Competitive Programmer. Analyze the problem statement and solution code, then output a JSON object adhering strictly to the schema. Include:
1. title (string)
2. algorithm_tags (array of strings)
3. approach_explanation (string)
4. code_breakdown (array of objects with step, section_title, explanation)
5. complexity_analysis (object with time_complexity, time_justification, space_complexity, space_justification)
6. code_quality (object with score 0-100, rating_label, strengths, edge_cases_handled, best_practices_feedback)
7. optimization_and_alternatives (array of objects with approach_name, time_complexity, space_complexity, tradeoffs)`;
const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`;
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
system_instruction: { parts: [{ text: systemInstruction }] },
contents: [{ parts: [{ text: promptText }] }],
generationConfig: {
response_mime_type: "application/json",
temperature: 0.2
}
})
});
if (!res.ok) {
throw new Error(`Gemini API Error: ${res.status} ${res.statusText}`);
}
const jsonRes = await res.json();
const rawText = jsonRes.candidates[0].content.parts[0].text;
const insightsData = JSON.parse(rawText);
insightsData.model = "gemini-1.5-flash (live client)";
return insightsData;
}
function copyCode() {
if (!rawCode) return;
navigator.clipboard.writeText(rawCode).then(() => {
const label = document.getElementById("copy-label");
label.textContent = "Copied";
setTimeout(() => {
label.textContent = "Copy";
}, 1800);
});
}
</script>
</body>
</html>