Spaces:
Sleeping

File size: 25,863 Bytes
cd7f8cb
3291af3
c276c5c
3291af3
a036603
3291af3
 
 
e2ecf05
a036603
 
 
3291af3
 
5f57b76
3291af3
 
35be66e
6aff5e9
694864c
3291af3
6aff5e9
694864c
8db608c
 
 
6aff5e9
 
8db608c
 
 
fc10d15
 
6aff5e9
99e0781
fc10d15
8db608c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc10d15
6aff5e9
 
8db608c
fc10d15
 
6aff5e9
 
 
8db608c
 
 
6aff5e9
fc10d15
8db608c
 
99e0781
6aff5e9
 
cf98be7
6aff5e9
8db608c
 
 
6aff5e9
 
 
8db608c
6aff5e9
 
 
8db608c
 
 
6aff5e9
8db608c
 
 
99e0781
6aff5e9
 
 
99e0781
6aff5e9
 
 
 
99e0781
6aff5e9
 
8db608c
6aff5e9
 
fc10d15
99e0781
6aff5e9
 
 
 
 
 
 
 
 
 
fc10d15
99e0781
8db608c
6aff5e9
 
 
fc10d15
6aff5e9
 
 
8db608c
 
6aff5e9
 
 
3291af3
c276c5c
3291af3
 
8db608c
 
 
 
 
 
 
 
 
6aff5e9
fc10d15
8db608c
6aff5e9
8db608c
fc10d15
 
8db608c
6aff5e9
a036603
 
 
35be66e
6aff5e9
8db608c
 
 
fc10d15
8db608c
35be66e
 
99e0781
6aff5e9
fc10d15
6aff5e9
fc10d15
6aff5e9
8db608c
fc10d15
 
6aff5e9
fc10d15
 
8c9b997
a036603
6aff5e9
 
fc10d15
6aff5e9
fc10d15
a036603
6aff5e9
 
a036603
 
3291af3
cc4179b
3291af3
8db608c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e0781
6aff5e9
876a6c3
8db608c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e0781
 
 
8db608c
99e0781
8db608c
99e0781
6aff5e9
 
99e0781
6aff5e9
 
8db608c
99e0781
6aff5e9
 
8db608c
6aff5e9
 
8db608c
 
 
 
99e0781
a036603
fc10d15
 
 
 
 
a036603
694864c
fc10d15
 
8db608c
fc10d15
a5df5b0
fc10d15
99e0781
fc10d15
6aff5e9
fc10d15
8db608c
fc10d15
 
99e0781
fc10d15
 
 
 
 
 
 
99e0781
fc10d15
99e0781
fc10d15
99e0781
6aff5e9
fc10d15
 
6aff5e9
fc10d15
a5df5b0
 
 
cf98be7
6aff5e9
99e0781
 
 
 
fc10d15
 
 
 
 
 
99e0781
fc10d15
99e0781
fc10d15
 
99e0781
fc10d15
6aff5e9
99e0781
 
fc10d15
 
 
 
 
 
 
 
99e0781
 
 
 
 
 
 
6aff5e9
99e0781
 
 
fc10d15
6aff5e9
fc10d15
 
cf98be7
fc10d15
99e0781
 
 
 
 
 
 
 
6aff5e9
99e0781
 
 
 
 
 
 
 
8db608c
 
 
 
 
99e0781
3291af3
 
 
 
 
 
fc10d15
 
3291af3
c276c5c
 
fc10d15
 
 
 
 
 
 
 
 
 
99e0781
fc10d15
 
 
 
 
 
 
 
 
99e0781
3291af3
99e0781
fc10d15
 
 
 
 
99e0781
fc10d15
 
 
 
 
3291af3
a036603
 
fc10d15
 
99e0781
fc10d15
 
 
 
99e0781
 
fc10d15
a036603
fc10d15
a036603
fc10d15
 
 
99e0781
fc10d15
99e0781
a036603
fc10d15
 
99e0781
a036603
3291af3
fc10d15
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
import os
import subprocess
import tempfile
from flask import Flask, render_template_string, request, jsonify
from groq import Groq

app = Flask(__name__)

# Exypos AI üçün Groq API
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
client_groq = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="az">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Twenty IDE | Premium Workspace</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* --- PREMIUM MINIMALIST DARK THEME --- */
        :root {
            --bg-base: #09090b; 
            --bg-panel: #18181b; 
            --border-color: #27272a; 
            --text-main: #fafafa;
            --text-muted: #a1a1aa;
            --accent: #e4e4e7; 
            --ai-accent: #8b5cf6; 
            --radius: 6px; 
        }

        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Inter', system-ui, -apple-system, sans-serif; }
        body { background-color: var(--bg-base); color: var(--text-main); height: 100vh; display: flex; flex-direction: column; overflow: hidden; }

        /* --- SADE "2 0" ANIMASIYASI --- */
        #splash {
            position: fixed; inset: 0; background: var(--bg-base); z-index: 9999;
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            transition: opacity 0.5s ease-out;
        }
        .logo-container {
            display: flex; font-size: 80px; font-weight: 700; color: var(--text-main); font-family: 'JetBrains Mono', monospace;
            overflow: hidden;
            animation: syncWave 0.6s 0.6s cubic-bezier(0.25, 1, 0.5, 1);
        }
        .digit-2 { transform: translateX(-200px); opacity: 0; animation: slideHit 0.6s cubic-bezier(0.25, 1, 0.5, 1) forwards; }
        .digit-0 { transform: translateX(0); }
        .logo-text {
            font-size: 14px; letter-spacing: 12px; margin-top: 15px; opacity: 0; color: var(--text-muted); text-transform: uppercase;
            animation: fadeInText 1s 1s forwards; margin-left: 12px;
        }
        
        @keyframes slideHit {
            0% { transform: translateX(-200px); opacity: 0; }
            100% { transform: translateX(0); opacity: 1; }
        }
        @keyframes syncWave {
            0% { transform: translateX(0) scale(1); }
            25% { transform: translateX(8px) scale(1.02); }
            50% { transform: translateX(-4px) scale(0.98); }
            75% { transform: translateX(4px) scale(1.01); }
            100% { transform: translateX(0) scale(1); }
        }
        @keyframes fadeInText {
            0% { opacity: 0; letter-spacing: 8px; }
            100% { opacity: 1; letter-spacing: 16px; }
        }

        /* --- PANELLƏR VƏ LAYOUT --- */
        .panel {
            background: var(--bg-panel); border: 1px solid var(--border-color); border-radius: var(--radius);
        }

        .top-bar { height: 50px; margin: 8px 8px 0 8px; display: flex; justify-content: space-between; align-items: center; padding: 0 16px; border: 1px solid var(--border-color); background: var(--bg-panel); border-radius: var(--radius); }
        .main-layout { display: flex; flex: 1; overflow: hidden; padding: 8px; gap: 8px; }
        
        .sidebar-left { width: 260px; display: flex; flex-direction: column; transition: width 0.3s, opacity 0.3s, padding 0.3s; white-space: nowrap; overflow: hidden; }
        .sidebar-right { width: 340px; display: flex; flex-direction: column; border-top: 2px solid var(--ai-accent); transition: width 0.3s, opacity 0.3s, padding 0.3s; white-space: nowrap; overflow: hidden; }
        .center-panel { flex: 1; display: flex; flex-direction: column; min-width: 0; transition: flex 0.3s; }
        .bottom-panel { height: 280px; display: flex; flex-direction: column; border-radius: var(--radius); margin-top: 8px; }

        .collapsed { width: 0 !important; padding: 0 !important; opacity: 0 !important; border: none !important; margin: 0 !important; }

        /* --- UI ELEMENTLƏRİ --- */
        .brand { font-size: 13px; font-weight: 600; letter-spacing: 1px; display: flex; align-items: center; gap: 10px; color: var(--text-main); }
        .brand span { color: var(--text-muted); font-weight: 400; }
        
        .controls { display: flex; align-items: center; gap: 8px; }
        .icon-btn { background: transparent; color: var(--text-muted); border: none; font-size: 14px; cursor: pointer; transition: 0.2s; padding: 4px; border-radius: 4px; }
        .icon-btn:hover { color: var(--text-main); background: #27272a; }

        .btn { background: transparent; color: var(--text-main); border: 1px solid var(--border-color); padding: 6px 12px; border-radius: 4px; cursor: pointer; transition: 0.2s; font-size: 12px; font-weight: 500; display: flex; align-items: center; gap: 6px; }
        .btn:hover { background: #27272a; border-color: #3f3f46; }
        .btn-run { background: var(--text-main); color: var(--bg-base); border: none; font-weight: 600; }
        .btn-run:hover { background: #e4e4e7; } 

        .panel-header { padding: 12px 16px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; color: var(--text-muted); border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }
        
        /* Explorer (Sol Panel - VFS) */
        #file-tree { flex: 1; padding: 12px; font-size: 13px; color: var(--text-main); overflow-y: auto; }
        .file-item { display: flex; justify-content: space-between; align-items: center; padding: 6px 8px; border-radius: 4px; cursor: pointer; color: var(--text-muted); transition: 0.1s; }
        .file-item:hover { background: #27272a; color: var(--text-main); }
        .file-item.active { background: #27272a; color: var(--text-main); font-weight: 500; border-left: 2px solid var(--accent); }
        .del-btn { opacity: 0; color: #ef4444; transition: 0.2s; font-size: 12px; }
        .file-item:hover .del-btn { opacity: 1; }

        /* Editor Area */
        #editor-container { flex: 1; background: var(--bg-panel); border-radius: var(--radius); overflow: hidden; border: 1px solid var(--border-color); }
        
        /* Terminal & Tabs */
        .bottom-tabs { display: flex; border-bottom: 1px solid var(--border-color); background: #121214; border-radius: var(--radius) var(--radius) 0 0; }
        .tab { padding: 10px 20px; font-size: 12px; cursor: pointer; color: var(--text-muted); transition: 0.2s; border-right: 1px solid var(--border-color); }
        .tab.active { color: var(--text-main); border-bottom: 2px solid var(--accent); background: var(--bg-panel); }
        .tab-content { flex: 1; overflow: hidden; display: none; background: var(--bg-panel); border-radius: 0 0 var(--radius) var(--radius); }
        .tab-content.active { display: flex; flex-direction: column; }
        
        #terminal-output { flex: 1; padding: 16px; font-family: 'JetBrains Mono', 'Consolas', monospace; font-size: 13px; color: #d4d4d8; overflow-y: auto; white-space: pre-wrap; line-height: 1.6; }
        .ps-cmd { color: var(--text-main); font-weight: 600; }
        .ps-err { color: #ef4444; }
        .ps-ok { color: #22c55e; }
        
        /* Exypos AI Chat */
        #ai-chat { flex: 1; padding: 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; font-size: 13px; background: var(--bg-panel); }
        .msg { padding: 12px; border-radius: var(--radius); max-width: 95%; line-height: 1.6; border: 1px solid var(--border-color); }
        .msg.user { background: #1f1f22; align-self: flex-end; color: #e4e4e7; }
        .msg.ai { background: #121214; align-self: flex-start; color: #d4d4d8; border-left: 2px solid var(--ai-accent); }
        
        .ai-input-zone { padding: 12px; border-top: 1px solid var(--border-color); display: flex; gap: 8px; background: #121214; border-radius: 0 0 var(--radius) var(--radius); }
        .ai-input-zone input { flex: 1; background: var(--bg-panel); border: 1px solid var(--border-color); color: var(--text-main); padding: 10px 12px; border-radius: 4px; outline: none; transition: 0.2s; font-size: 13px; }
        .ai-input-zone input:focus { border-color: var(--ai-accent); }
        .send-btn { background: var(--text-main); color: var(--bg-base); border: none; border-radius: 4px; padding: 0 14px; cursor: pointer; transition: 0.2s; }
        .send-btn:hover { background: #e4e4e7; }
        
        /* AI Editor Actions */
        .ai-action-btn { background: var(--bg-base); color: var(--text-main); border: 1px solid var(--border-color); padding: 6px 10px; border-radius: 4px; font-size: 11px; font-weight: 500; cursor: pointer; margin-top: 8px; transition: 0.2s; display: inline-flex; align-items: center; gap: 6px; }
        .ai-action-btn:hover { border-color: var(--text-main); }
        .terminal-ai-btn { background: transparent; border: 1px solid #ef4444; color: #ef4444; padding: 4px 10px; border-radius: 4px; cursor: pointer; margin-top: 5px; font-size: 11px; transition: 0.2s; display: inline-flex; align-items: center; gap: 4px; }
        .terminal-ai-btn:hover { background: #ef4444; color: #fff; }
        
        pre { background: #000; padding: 12px; border-radius: 4px; overflow-x: auto; border: 1px solid var(--border-color); margin-top: 8px; }
        code { font-family: 'JetBrains Mono', 'Consolas', monospace; color: #e4e4e7; font-size: 12px; }

        /* Scrollbar */
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: var(--bg-base); }
        ::-webkit-scrollbar-thumb { background: #3f3f46; border-radius: 4px; }
        ::-webkit-scrollbar-thumb:hover { background: #52525b; }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.36.1/min/vs/loader.min.js"></script>
</head>
<body>

    <div id="splash">
        <div class="logo-container">
            <div class="digit-2">2</div>
            <div class="digit-0">0</div>
        </div>
        <div class="logo-text">TWENTY</div>
    </div>

    <div class="top-bar">
        <div class="brand">
            <button class="icon-btn" onclick="toggleSidebar('sidebar-left')" title="Explorer-i aç/bağla"><i class="fa-solid fa-folder-tree"></i></button>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 2 7 12 12 22 7 12 2"></polygon><polyline points="2 17 12 22 22 17"></polyline><polyline points="2 12 12 17 22 12"></polyline></svg>
            TWENTY OS <span id="current-file-label">/ main.py</span>
        </div>
        <div class="controls">
            <button class="icon-btn" onclick="toggleSidebar('sidebar-right')" title="Exypos-u aç/bağla"><i class="fa-solid fa-bolt" style="color: var(--ai-accent);"></i></button>
            <button class="btn btn-run" onclick="runCode()"><i class="fa-solid fa-play" style="font-size: 10px;"></i> Run Code</button>
        </div>
    </div>

    <div class="main-layout">
        <div class="panel sidebar-left" id="sidebar-left">
            <div class="panel-header">
                EXPLORER
                <i class="fa-solid fa-plus icon-btn" onclick="createFile()" title="Yeni Fayl"></i>
            </div>
            <div id="file-tree"></div>
        </div>

        <div class="center-panel">
            <div id="editor-container"></div>
            
            <div class="panel bottom-panel" id="bottom-panel">
                <div class="bottom-tabs">
                    <div class="tab active" onclick="switchTab('terminal')">Terminal</div>
                    <i class="fa-solid fa-broom icon-btn" style="margin-left:auto; margin-right:8px; margin-top:8px;" onclick="clearTerminal()" title="Clear"></i>
                </div>
                <div class="tab-content active" id="tab-terminal">
                    <div id="terminal-output"><span style="color:#52525b;">// Environment Ready.</span><br></div>
                </div>
            </div>
        </div>

        <div class="panel sidebar-right" id="sidebar-right">
            <div class="panel-header" style="color: var(--ai-accent); border-bottom-color: var(--border-color);"><i class="fa-solid fa-bolt" style="margin-right: 4px;"></i> EXYPOS AI</div>
            <div id="ai-chat">
                <div class="msg ai">Sistemlər aktivdir. Kodunu oxuyuram, xəta olarsa mənə göndər.</div>
            </div>
            <div class="ai-input-zone">
                <input type="text" id="ai-input" placeholder="Ask Exypos..." onkeypress="if(event.key === 'Enter') askAI()">
                <button class="send-btn" onclick="askAI()"><i class="fa-solid fa-arrow-up"></i></button>
            </div>
        </div>
    </div>

    <script>
        // --- SPLASH LOGIC ---
        window.onload = () => {
            setTimeout(() => {
                const splash = document.getElementById('splash');
                splash.style.opacity = '0';
                setTimeout(() => splash.remove(), 500); 
            }, 2600); // 2.6 saniyəyə bitir (Tez və Kəskin)
        };

        // --- VIRTUAL FILE SYSTEM (VFS) ---
        let vfs = {
            "main.py": "# Welcome to Twenty Premium Workspace\\ndef main():\\n    print('Hello, Engineer.')\\n\\nif __name__ == '__main__':\\n    main()",
            "utils.py": "def add(a, b):\\n    return a + b\\n"
        };
        let currentFile = "main.py";
        let editor;
        let lastAiCode = ""; 

        function renderVFS() {
            const tree = document.getElementById('file-tree');
            tree.innerHTML = "";
            for (let fileName in vfs) {
                const isActive = (fileName === currentFile) ? 'active' : '';
                const fileDiv = document.createElement('div');
                fileDiv.className = `file-item ${isActive}`;
                
                let iconColor = fileName.endsWith('.py') ? '#eab308' : '#a1a1aa';
                let iconClass = fileName.endsWith('.py') ? 'fa-brands fa-python' : 'fa-solid fa-file';
                
                fileDiv.innerHTML = `
                    <div style="display:flex; align-items:center; gap:8px; width:100%;" onclick="openFile('${fileName}')">
                        <i class="${iconClass}" style="color:${iconColor};"></i> <span style="flex:1; overflow:hidden; text-overflow:ellipsis;">${fileName}</span>
                    </div>
                    <i class="fa-solid fa-trash del-btn" onclick="deleteFile('${fileName}', event)"></i>
                `;
                tree.appendChild(fileDiv);
            }
            document.getElementById('current-file-label').innerText = `/ ${currentFile}`;
        }

        function openFile(fileName) {
            if (editor) vfs[currentFile] = editor.getValue();
            currentFile = fileName;
            let lang = fileName.endsWith('.py') ? 'python' : 'plaintext';
            monaco.editor.setModelLanguage(editor.getModel(), lang);
            editor.setValue(vfs[fileName]);
            renderVFS();
        }

        function createFile() {
            let name = prompt("Yeni faylın adı (məs: test.py):");
            if (name && !vfs[name]) {
                vfs[name] = "# " + name + "\\n";
                openFile(name);
            }
        }

        function deleteFile(fileName, event) {
            event.stopPropagation();
            if (Object.keys(vfs).length <= 1) {
                alert("Sonuncu faylı silə bilməzsiniz!");
                return;
            }
            if (confirm(`'${fileName}' silinsin?`)) {
                delete vfs[fileName];
                if (currentFile === fileName) {
                    openFile(Object.keys(vfs)[0]);
                } else {
                    renderVFS();
                }
            }
        }

        // --- PANELS TOGGLE LOGIC ---
        function toggleSidebar(id) {
            document.getElementById(id).classList.toggle('collapsed');
            // Editorun ölçüsünü yenidən hesablaması üçün qısa gecikmə
            setTimeout(() => { if (editor) editor.layout(); }, 350);
        }

        // --- MONACO EDITOR İNİT ---
        require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.36.1/min/vs' }});
        require(['vs/editor/editor.main'], function() {
            editor = monaco.editor.create(document.getElementById('editor-container'), {
                value: vfs[currentFile],
                language: 'python',
                theme: 'vs-dark',
                automaticLayout: true,
                fontSize: 14,
                fontFamily: "'JetBrains Mono', 'Consolas', monospace",
                minimap: { enabled: false },
                padding: { top: 16 },
                scrollBeyondLastLine: false,
                renderLineHighlight: "all"
            });
            
            monaco.editor.defineTheme('twenty-dark', {
                base: 'vs-dark', inherit: true, rules: [], colors: { 'editor.background': '#18181b' }
            });
            monaco.editor.setTheme('twenty-dark');
            
            // Kod dəyişdikcə VFS-i yenilə
            editor.onDidChangeModelContent(() => { vfs[currentFile] = editor.getValue(); });
            renderVFS();
        });

        function switchTab(tabId) {
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(tc => tc.classList.remove('active'));
            event.currentTarget.classList.add('active');
            document.getElementById(`tab-${tabId}`).classList.add('active');
        }

        async function runCode() {
            if(!editor) return;
            vfs[currentFile] = editor.getValue(); // Son dəyişikliyi yadda saxla
            const code = editor.getValue();
            const term = document.getElementById('terminal-output');
            const isShell = code.trim().startsWith('!');

            if(isShell) {
                term.innerHTML += `<br><span class="ps-cmd">$</span> ${code.trim()}<br><span style="color:#52525b">Executing...</span>`;
            } else {
                term.innerHTML += `<br><span class="ps-cmd">user@twenty:~$</span> python ${currentFile}<br><span style="color:#52525b">Executing...</span>`;
            }
            term.scrollTop = term.scrollHeight;

            try {
                const response = await fetch('/run', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ code: code, is_shell: isShell })
                });
                const data = await response.json();
                
                if (data.status === 'success') {
                    term.innerHTML += `<br><span class="ps-ok">${escapeHtml(data.output)}</span>`;
                } else {
                    let safeError = encodeURIComponent(data.output.substring(0, 500));
                    term.innerHTML += `<br><span class="ps-err">${escapeHtml(data.output)}</span><br><button class="terminal-ai-btn" onclick="askAiAboutError('${safeError}')"><i class="fa-solid fa-bug"></i> Fix with Exypos</button>`;
                }
            } catch (error) {
                term.innerHTML += `<br><span class="ps-err">System Error!</span>`;
            }
            term.scrollTop = term.scrollHeight;
        }

        function clearTerminal() {
            document.getElementById('terminal-output').innerHTML = `<span class="ps-cmd">user@twenty:~$</span> Clear...`;
        }

        function escapeHtml(text) {
            return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }

        async function askAI() {
            const inputEl = document.getElementById('ai-input');
            const prompt = inputEl.value.trim();
            if(!prompt) return;

            const chat = document.getElementById('ai-chat');
            chat.innerHTML += `<div class="msg user">${escapeHtml(prompt)}</div>`;
            inputEl.value = '';
            chat.scrollTop = chat.scrollHeight;

            const typingId = "type-" + Date.now();
            chat.innerHTML += `<div class="msg ai" id="${typingId}">Thinking...</div>`;
            chat.scrollTop = chat.scrollHeight;

            try {
                const contextCode = editor ? editor.getValue() : "";
                const response = await fetch('/ask_ai', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ prompt: prompt, code: contextCode })
                });
                const data = await response.json();
                
                let rawReply = escapeHtml(data.reply);
                
                const codeMatch = data.reply.match(/```(?:python)?\\n([\\s\\S]*?)```/);
                if(codeMatch) {
                    lastAiCode = codeMatch[1].trim();
                    rawReply = rawReply.replace(/```(?:python)?\\n([\\s\\S]*?)```/g, 
                        `</p><pre><code>$1</code></pre><button class="ai-action-btn" onclick="insertAiCode()"><i class="fa-solid fa-download"></i> Apply to Editor</button><p>`);
                }

                document.getElementById(typingId).innerHTML = rawReply.replace(/\\n/g, '<br>');
            } catch (e) {
                document.getElementById(typingId).innerHTML = "<span style='color:#ef4444'>Connection Error.</span>";
            }
            chat.scrollTop = chat.scrollHeight;
        }

        function insertAiCode() {
            if(editor && lastAiCode) {
                const selection = editor.getSelection();
                editor.executeEdits("ai-insert", [{
                    range: selection,
                    text: lastAiCode,
                    forceMoveMarkers: true
                }]);
                document.getElementById('terminal-output').innerHTML += `<br><span style="color:var(--ai-accent)">[Exypos AI]</span> Code applied successfully.<br>`;
            }
        }

        function askAiAboutError(encodedError) {
            const decodedError = decodeURIComponent(encodedError);
            const inputEl = document.getElementById('ai-input');
            inputEl.value = "Bu xətanı necə həll edim? Xəta: " + decodedError;
            askAI();
            // Xəta soruşanda avtomatik AI panelini açır
            const aiPanel = document.getElementById('sidebar-right');
            if(aiPanel.classList.contains('collapsed')) {
                toggleSidebar('sidebar-right');
            }
        }
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/run', methods=['POST'])
def run_code():
    data = request.json
    code = data.get('code', '')
    is_shell = data.get('is_shell', False)
    
    if not code.strip():
        return jsonify({"status": "error", "output": "Boş kod göndərildi."})
        
    if is_shell:
        shell_cmd = code.strip()[1:] 
        try:
            result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True, timeout=60)
            output = result.stdout if result.returncode == 0 else result.stderr
            status = "success" if result.returncode == 0 else "error"
            return jsonify({"status": status, "output": output})
        except Exception as e:
            return jsonify({"status": "error", "output": str(e)})

    with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as temp_file:
        temp_file.write(code)
        temp_filepath = temp_file.name

    try:
        result = subprocess.run(['python', temp_filepath], capture_output=True, text=True, timeout=15)
        if result.returncode == 0:
            return jsonify({"status": "success", "output": result.stdout})
        else:
            return jsonify({"status": "error", "output": result.stderr if result.stderr else result.stdout})
    except subprocess.TimeoutExpired:
        return jsonify({"status": "error", "output": "Vaxt bitdi (15 saniyə limit). Sonsuz dövrə (while True) düşmüş ola bilərsiniz."})
    except Exception as e:
        return jsonify({"status": "error", "output": str(e)})
    finally:
        if os.path.exists(temp_filepath):
            os.remove(temp_filepath)

@app.route('/ask_ai', methods=['POST'])
def ask_ai():
    if not client_groq:
        return jsonify({"reply": "Xəta: Groq API Key (GROQ_API_KEY) tapılmadı."})
        
    data = request.json
    prompt = data.get('prompt', '')
    context_code = data.get('code', '')
    
    system_msg = "Sən Exypos AI-san, Twenty OS daxilində çalışan güclü kod köməkçisisən. Qısa, dəqiq və azərbaycanca cavab ver. Əgər kod düzəldirsənsə, mütləq mətndə yalnız python kodunu ```python ... ``` blokunun içinə yaz."
    user_msg = f"Sual: {prompt}\n\nHazırki kodum:\n```python\n{context_code}\n```"
    
    try:
        chat_completion = client_groq.chat.completions.create(
            messages=[
                {"role": "system", "content": system_msg},
                {"role": "user", "content": user_msg}
            ],
            model="llama-3.1-8b-instant",
            temperature=0.5,
            max_tokens=1500
        )
        return jsonify({"reply": chat_completion.choices[0].message.content})
    except Exception as e:
        return jsonify({"reply": f"AI Bağlantı Xətası: {str(e)}"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860, debug=False)