File size: 30,229 Bytes
6ddb7a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
import gradio as gr
import json
import os
import re
import time
import uuid
from datetime import datetime
from typing import Dict, List, Tuple, Any, Optional
import subprocess
import tempfile
import shutil

class CodeExecutionEnvironment:
    """Safe code execution environment with sandboxing"""
    
    def __init__(self):
        self.temp_dir = tempfile.mkdtemp()
        self.history = []
        
    def execute_code(self, code: str, language: str = "python") -> Dict[str, Any]:
        """Execute code in a sandboxed environment"""
        execution_id = str(uuid.uuid4())[:8]
        timestamp = datetime.now().isoformat()
        
        try:
            if language.lower() == "python":
                result = self._execute_python(code)
            elif language.lower() == "javascript":
                result = self._execute_javascript(code)
            elif language.lower() == "bash":
                result = self._execute_bash(code)
            else:
                result = {"output": f"Language {language} not supported", "error": True}
            
            execution_record = {
                "id": execution_id,
                "timestamp": timestamp,
                "code": code,
                "language": language,
                "result": result
            }
            self.history.append(execution_record)
            
            return result
            
        except Exception as e:
            return {
                "output": f"Execution error: {str(e)}",
                "error": True,
                "execution_id": execution_id
            }
    
    def _execute_python(self, code: str) -> Dict[str, Any]:
        """Execute Python code safely"""
        try:
            # Create a temporary file
            temp_file = os.path.join(self.temp_dir, f"temp_{uuid.uuid4()}.py")
            with open(temp_file, 'w') as f:
                f.write(code)
            
            # Execute with timeout
            result = subprocess.run(
                ['python', temp_file],
                capture_output=True,
                text=True,
                timeout=30,
                cwd=self.temp_dir
            )
            
            return {
                "output": result.stdout,
                "error": result.returncode != 0,
                "stderr": result.stderr if result.stderr else None
            }
        except subprocess.TimeoutExpired:
            return {"output": "Code execution timed out (30s limit)", "error": True}
        except Exception as e:
            return {"output": f"Python execution error: {str(e)}", "error": True}
    
    def _execute_javascript(self, code: str) -> Dict[str, Any]:
        """Execute JavaScript code using Node.js"""
        try:
            temp_file = os.path.join(self.temp_dir, f"temp_{uuid.uuid4()}.js")
            with open(temp_file, 'w') as f:
                f.write(code)
            
            result = subprocess.run(
                ['node', temp_file],
                capture_output=True,
                text=True,
                timeout=30,
                cwd=self.temp_dir
            )
            
            return {
                "output": result.stdout,
                "error": result.returncode != 0,
                "stderr": result.stderr if result.stderr else None
            }
        except subprocess.TimeoutExpired:
            return {"output": "Code execution timed out (30s limit)", "error": True}
        except FileNotFoundError:
            return {"output": "Node.js not found. Please install Node.js to run JavaScript.", "error": True}
        except Exception as e:
            return {"output": f"JavaScript execution error: {str(e)}", "error": True}
    
    def _execute_bash(self, code: str) -> Dict[str, Any]:
        """Execute bash commands"""
        try:
            result = subprocess.run(
                code,
                shell=True,
                capture_output=True,
                text=True,
                timeout=30,
                cwd=self.temp_dir
            )
            
            return {
                "output": result.stdout,
                "error": result.returncode != 0,
                "stderr": result.stderr if result.stderr else None
            }
        except subprocess.TimeoutExpired:
            return {"output": "Command execution timed out (30s limit)", "error": True}
        except Exception as e:
            return {"output": f"Bash execution error: {str(e)}", "error": True}
    
    def cleanup(self):
        """Clean up temporary files"""
        try:
            shutil.rmtree(self.temp_dir)
        except:
            pass

class AICodeAssistant:
    """AI-powered code generation and assistance"""
    
    def __init__(self):
        self.templates = {
            "react": """import React from 'react';

function Component() {{
  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
}}

export default Component;""",
            "python": """def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()""",
            "fastapi": """from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {{"message": "Hello World"}}""",
            "gradio": """import gradio as gr

def greet(name):
    return f"Hello {name}!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()""",
            "express": """const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.json({ message: 'Hello World!' });
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});""",
        }
    
    def generate_code(self, prompt: str, language: str, context: str = "") -> str:
        """Generate code based on prompt and language"""
        # Enhanced code generation with context awareness
        language = language.lower()
        
        # Check for template usage
        if any(template in prompt.lower() for template in ["react", "component", "jsx"]):
            return self.templates["react"]
        elif "fastapi" in prompt.lower():
            return self.templates["fastapi"]
        elif "gradio" in prompt.lower():
            return self.templates["gradio"]
        elif "express" in prompt.lower():
            return self.templates["express"]
        elif "python" in prompt.lower() or language == "python":
            return self.templates["python"]
        
        # Generate code based on common patterns
        if "function" in prompt.lower() or "def" in prompt.lower():
            if language == "python":
                return f"""def {prompt.split()[-1] if prompt.split() else 'function_name'}():
    # TODO: Implement function
    pass

# Example usage
if __name__ == "__main__":
    result = {prompt.split()[-1] if prompt.split() else 'function_name'}()
    print(result)"""
            elif language in ["javascript", "js"]:
                return f"""function {prompt.split()[-1] if prompt.split() else 'functionName'}() {{
    // TODO: Implement function
    console.log("Function called");
}}

// Example usage
{prompt.split()[-1] if prompt.split() else 'functionName'}();"""
        
        # Default response
        return f"""// Generated code for: {prompt}
// Language: {language}

// TODO: Implement your solution here
console.log("Code generated for: {prompt}");"""
    
    def explain_code(self, code: str) -> str:
        """Provide explanation for code"""
        lines = code.split('\n')
        explanation = "Code Analysis:\n\n"
        
        # Simple pattern-based explanation
        for i, line in enumerate(lines[:10], 1):  # Limit to first 10 lines
            line = line.strip()
            if not line or line.startswith('//') or line.startswith('#'):
                continue
            
            if 'def ' in line:
                explanation += f"Line {i}: Function definition - {line}\n"
            elif 'function ' in line:
                explanation += f"Line {i}: Function declaration - {line}\n"
            elif 'import ' in line:
                explanation += f"Line {i}: Import statement - {line}\n"
            elif 'class ' in line:
                explanation += f"Line {i}: Class definition - {line}\n"
            elif '=' in line:
                explanation += f"Line {i}: Variable assignment - {line}\n"
            else:
                explanation += f"Line {i}: Code statement - {line}\n"
        
        return explanation + "\nThis is a basic analysis. For detailed explanations, consider adding more context."
    
    def debug_code(self, code: str, error_message: str) -> str:
        """Provide debugging suggestions"""
        suggestions = [
            "Check for syntax errors and typos",
            "Verify all variables are properly declared",
            "Ensure proper indentation",
            "Check for missing imports or dependencies",
            "Review logic flow and control structures"
        ]
        
        debug_help = f"Debugging Suggestions for Error: {error_message}\n\n"
        debug_help += "\n".join(f"β€’ {suggestion}" for suggestion in suggestions)
        
        # Add specific suggestions based on error patterns
        if "syntax" in error_message.lower():
            debug_help += "\n\nSyntax Error Specific:\nβ€’ Check for missing colons, brackets, or quotes\nβ€’ Verify proper indentation"
        elif "undefined" in error_message.lower():
            debug_help += "\n\nUndefined Error Specific:\nβ€’ Check variable scope\nβ€’ Ensure variables are declared before use"
        elif "import" in error_message.lower():
            debug_help += "\n\nImport Error Specific:\nβ€’ Verify module names are correct\nβ€’ Check if required packages are installed"
        
        return debug_help

class CodeIDE:
    """Main IDE application"""
    
    def __init__(self):
        self.executor = CodeExecutionEnvironment()
        self.assistant = AICodeAssistant()
        self.current_file = None
        self.files = {}
        self.chat_history = []
        
    def create_new_file(self, filename: str, content: str = "") -> str:
        """Create a new file"""
        if not filename:
            return "Error: Filename cannot be empty"
        
        self.files[filename] = content
        self.current_file = filename
        return f"Created file: {filename}"
    
    def save_file(self, filename: str, content: str) -> str:
        """Save file content"""
        self.files[filename] = content
        return f"Saved: {filename}"
    
    def load_file(self, filename: str) -> Tuple[str, str]:
        """Load file content"""
        if filename in self.files:
            self.current_file = filename
            return self.files[filename], f"Loaded: {filename}"
        else:
            return "", f"File not found: {filename}"
    
    def delete_file(self, filename: str) -> str:
        """Delete a file"""
        if filename in self.files:
            del self.files[filename]
            if self.current_file == filename:
                self.current_file = None
            return f"Deleted: {filename}"
        else:
            return f"File not found: {filename}"
    
    def get_file_list(self) -> List[str]:
        """Get list of all files"""
        return list(self.files.keys())
    
    def generate_code_response(self, message: str, language: str, current_code: str = "") -> str:
        """Generate AI response for code generation"""
        response = self.assistant.generate_code(message, language, current_code)
        
        # Add to chat history
        self.chat_history.append({"role": "user", "content": message})
        self.chat_history.append({"role": "assistant", "content": response})
        
        return response
    
    def explain_code_response(self, code: str) -> str:
        """Explain code with AI"""
        explanation = self.assistant.explain_code(code)
        
        self.chat_history.append({"role": "user", "content": "Explain this code"})
        self.chat_history.append({"role": "assistant", "content": explanation})
        
        return explanation
    
    def debug_code_response(self, code: str, error: str) -> str:
        """Debug code with AI"""
        debug_suggestion = self.assistant.debug_code(code, error)
        
        self.chat_history.append({"role": "user", "content": f"Debug this error: {error}"})
        self.chat_history.append({"role": "assistant", "content": debug_suggestion})
        
        return debug_suggestion
    
    def execute_current_code(self, code: str, language: str) -> Dict[str, Any]:
        """Execute the current code"""
        result = self.executor.execute_code(code, language)
        return result
    
    def get_chat_history(self) -> List[Dict[str, str]]:
        """Get chat history"""
        return self.chat_history
    
    def clear_chat_history(self) -> str:
        """Clear chat history"""
        self.chat_history = []
        return "Chat history cleared"

# Initialize IDE
ide = CodeIDE()

def create_interface():
    """Create the Gradio interface"""
    
    with gr.Blocks(
        title="AnyCoder - AI Code Generation IDE",
        theme=gr.themes.Soft(),
        css="""
        .header { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px; 
            border-radius: 10px; 
            margin-bottom: 20px;
            text-align: center;
        }
        .header h1 { 
            color: white; 
            margin: 0;
            font-size: 2.5em;
        }
        .header p { 
            color: rgba(255,255,255,0.9); 
            margin: 10px 0 0 0;
            font-size: 1.1em;
        }
        .header a {
            color: white;
            text-decoration: underline;
        }
        .code-editor {
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        .chat-container {
            height: 400px;
            overflow-y: auto;
        }
        """
    ) as demo:
        
        with gr.Row():
            gr.HTML("""
            <div class="header">
                <h1>πŸš€ AnyCoder</h1>
                <p>Uncensored AI Code Generation IDE with Conversational Assistant</p>
                <p>Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">anycoder</a></p>
            </div>
            """)
        
        with gr.Tabs() as tabs:
            
            # Code Editor Tab
            with gr.TabItem("πŸ’» Code Editor", id="editor"):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### πŸ“ File Manager")
                        file_list = gr.Dropdown(
                            choices=ide.get_file_list(),
                            label="Select File",
                            interactive=True
                        )
                        new_file_name = gr.Textbox(label="New File Name", placeholder="example.py")
                        with gr.Row():
                            create_btn = gr.Button("πŸ“„ New", variant="primary")
                            save_btn = gr.Button("πŸ’Ύ Save", variant="secondary")
                            delete_btn = gr.Button("πŸ—‘οΈ Delete", variant="stop")
                        
                        gr.Markdown("### βš™οΈ Settings")
                        language_select = gr.Dropdown(
                            choices=["python", "javascript", "bash", "html", "css"],
                            value="python",
                            label="Language"
                        )
                        with gr.Row():
                            run_btn = gr.Button("▢️ Run Code", variant="primary")
                            clear_btn = gr.Button("🧹 Clear")
                    
                    with gr.Column(scale=2):
                        gr.Markdown("### πŸ“ Code Editor")
                        code_editor = gr.Code(
                            label="Code",
                            language="python",
                            lines=20,
                            elem_classes=["code-editor"]
                        )
                        
                        gr.Markdown("### πŸ“Š Output")
                        output_display = gr.Code(
                            label="Execution Output",
                            language="text",
                            lines=10,
                            interactive=False
                        )
            
            # AI Assistant Tab
            with gr.TabItem("πŸ€– AI Assistant", id="assistant"):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### πŸ’¬ Chat with AI")
                        chatbot = gr.Chatbot(
                            type="messages",
                            elem_classes=["chat-container"],
                            height=400
                        )
                        
                        with gr.Row():
                            msg_input = gr.Textbox(
                                label="Ask for code help...",
                                placeholder="Generate a React component for a todo list",
                                lines=2
                            )
                            send_btn = gr.Button("πŸ“€ Send", variant="primary")
                        
                        with gr.Row():
                            clear_chat_btn = gr.Button("🧹 Clear Chat")
                            explain_btn = gr.Button("πŸ“– Explain Code")
                            debug_btn = gr.Button("πŸ› Debug Code")
                    
                    with gr.Column(scale=1):
                        gr.Markdown("### 🎯 Quick Actions")
                        with gr.Accordion("Code Templates", open=True):
                            template_select = gr.Dropdown(
                                choices=["React Component", "FastAPI", "Gradio", "Express", "Python Function"],
                                label="Select Template",
                                value="React Component"
                            )
                            use_template_btn = gr.Button("πŸ“‹ Use Template", variant="secondary")
                        
                        gr.Markdown("### πŸ› οΈ AI Tools")
                        ai_language = gr.Dropdown(
                            choices=["python", "javascript", "react", "html", "css"],
                            value="python",
                            label="Target Language"
                        )
                        
                        gr.Markdown("### πŸ“š Recent History")
                        history_display = gr.JSON(
                            label="Chat History",
                            value=ide.get_chat_history()
                        )
            
            # Project Files Tab
            with gr.TabItem("πŸ“‚ Project Files", id="files"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### πŸ“‹ All Files")
                        files_display = gr.DataFrame(
                            headers=["Filename", "Size", "Type"],
                            datatype=["str", "str", "str"],
                            interactive=False
                        )
                        
                        refresh_files_btn = gr.Button("πŸ”„ Refresh Files", variant="primary")
                        
                        gr.Markdown("### πŸ“€ Export Project")
                        export_format = gr.Dropdown(
                            choices=["ZIP", "JSON"],
                            value="ZIP",
                            label="Export Format"
                        )
                        export_btn = gr.Button("πŸ“¦ Export Project")
                        
                        gr.Markdown("### πŸ“₯ Import Project")
                        import_file = gr.File(
                            label="Import Project File",
                            file_types=[".zip", ".json"]
                        )
                        import_btn = gr.Button("πŸ“₯ Import")
                    
                    with gr.Column():
                        gr.Markdown("### πŸ“Š Project Statistics")
                        stats_display = gr.JSON(
                            label="Statistics",
                            value={}
                        )
                        
                        gr.Markdown("### πŸ• Execution History")
                        exec_history = gr.DataFrame(
                            headers=["Time", "Language", "Status"],
                            datatype=["str", "str", "str"],
                            interactive=False
                        )
            
            # Settings Tab
            with gr.TabItem("βš™οΈ Settings", id="settings"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### 🎨 Theme Settings")
                        theme_select = gr.Dropdown(
                            choices=["Soft", "Base", "Default", "Monochrome"],
                            value="Soft",
                            label="Theme"
                        )
                        
                        gr.Markdown("### πŸ”§ Editor Settings")
                        font_size = gr.Slider(
                            minimum=10,
                            maximum=24,
                            value=14,
                            step=1,
                            label="Font Size"
                        )
                        tab_size = gr.Slider(
                            minimum=2,
                            maximum=8,
                            value=4,
                            step=1,
                            label="Tab Size"
                        )
                        
                        gr.Markdown("### πŸ€– AI Settings")
                        ai_temperature = gr.Slider(
                            minimum=0.1,
                            maximum=1.0,
                            value=0.7,
                            step=0.1,
                            label="AI Creativity"
                        )
                        max_tokens = gr.Slider(
                            minimum=100,
                            maximum=2000,
                            value=1000,
                            step=100,
                            label="Max Response Length"
                        )
                    
                    with gr.Column():
                        gr.Markdown("### πŸš€ Advanced Settings")
                        auto_save = gr.Checkbox(
                            label="Auto-save files",
                            value=True
                        )
                        line_numbers = gr.Checkbox(
                            label="Show line numbers",
                            value=True
                        )
                        word_wrap = gr.Checkbox(
                            label="Word wrap",
                            value=False
                        )
                        
                        gr.Markdown("### πŸ”„ Reset Options")
                        with gr.Row():
                            reset_settings_btn = gr.Button("πŸ”„ Reset Settings", variant="secondary")
                            clear_all_btn = gr.Button("πŸ—‘οΈ Clear All Data", variant="stop")
        
        # Event Handlers
        def create_file(filename):
            if filename:
                result = ide.create_new_file(filename)
                return result, gr.Dropdown(choices=ide.get_file_list(), value=filename)
            return "Please enter a filename", gr.Dropdown()
        
        def save_file(filename, content):
            if filename:
                return ide.save_file(filename, content)
            return "No file selected"
        
        def load_file(filename):
            if filename:
                content, message = ide.load_file(filename)
                return content, message
            return "", "No file selected"
        
        def delete_file(filename):
            if filename:
                result = ide.delete_file(filename)
                return result, gr.Dropdown(choices=ide.get_file_list())
            return "No file selected", gr.Dropdown()
        
        def run_code(code, language):
            if code:
                result = ide.execute_current_code(code, language)
                output = result.get("output", "")
                if result.get("error"):
                    output = f"ERROR:\n{output}\n\nSTDERR:\n{result.get('stderr', '')}"
                return output
            return "No code to run"
        
        def chat_response(message, history, language, code):
            if not message:
                return "", history
            
            # Generate AI response
            response = ide.generate_code_response(message, language, code)
            history.append({"role": "user", "content": message})
            history.append({"role": "assistant", "content": response})
            
            return "", history
        
        def explain_current_code(code, history):
            if code:
                explanation = ide.explain_code_response(code)
                history.append({"role": "user", "content": "Explain the current code"})
                history.append({"role": "assistant", "content": explanation})
            return history
        
        def debug_current_code(code, history):
            if code:
                # Simulate finding an error
                debug_response = ide.debug_code_response(code, "Example error message")
                history.append({"role": "user", "content": "Debug the current code"})
                history.append({"role": "assistant", "content": debug_response})
            return history
        
        def use_template(template, language):
            template_map = {
                "React Component": "react",
                "FastAPI": "fastapi",
                "Gradio": "gradio",
                "Express": "express",
                "Python Function": "python"
            }
            template_key = template_map.get(template, "python")
            return ide.assistant.templates.get(template_key, "# Template not found")
        
        def clear_chat():
            ide.clear_chat_history()
            return []
        
        def refresh_files():
            files = ide.get_file_list()
            file_data = []
            for file in files:
                content = ide.files.get(file, "")
                file_data.append([file, f"{len(content)} chars", file.split('.')[-1] if '.' in file else "text"])
            return file_data
        
        def update_stats():
            files = ide.get_file_list()
            total_chars = sum(len(ide.files.get(f, "")) for f in files)
            return {
                "total_files": len(files),
                "total_characters": total_chars,
                "languages": list(set(f.split('.')[-1] if '.' in f else "text" for f in files)),
                "chat_messages": len(ide.chat_history)
            }
        
        def get_exec_history():
            history = []
            for record in ide.executor.history[-10:]:  # Last 10 executions
                status = "βœ… Success" if not record["result"].get("error") else "❌ Error"
                history.append([record["timestamp"], record["language"], status])
            return history
        
        # Wire up events
        create_btn.click(
            create_file,
            inputs=[new_file_name],
            outputs=[gr.Textbox(label="Status"), file_list]
        )
        
        save_btn.click(
            save_file,
            inputs=[file_list, code_editor],
            outputs=[gr.Textbox(label="Status")]
        )
        
        file_list.change(
            load_file,
            inputs=[file_list],
            outputs=[code_editor, gr.Textbox(label="Status")]
        )
        
        delete_btn.click(
            delete_file,
            inputs=[file_list],
            outputs=[gr.Textbox(label="Status"), file_list]
        )
        
        run_btn.click(
            run_code,
            inputs=[code_editor, language_select],
            outputs=[output_display]
        )
        
        clear_btn.click(
            lambda: ("", ""),
            outputs=[code_editor, output_display]
        )
        
        send_btn.click(
            chat_response,
            inputs=[msg_input, chatbot, ai_language, code_editor],
            outputs=[msg_input, chatbot]
        )
        
        msg_input.submit(
            chat_response,
            inputs=[msg_input, chatbot, ai_language, code_editor],
            outputs=[msg_input, chatbot]
        )
        
        clear_chat_btn.click(
            clear_chat,
            outputs=[chatbot]
        )
        
        explain_btn.click(
            explain_current_code,
            inputs=[code_editor, chatbot],
            outputs=[chatbot]
        )
        
        debug_btn.click(
            debug_current_code,
            inputs=[code_editor, chatbot],
            outputs=[chatbot]
        )
        
        use_template_btn.click(
            use_template,
            inputs=[template_select, ai_language],
            outputs=[code_editor]
        )
        
        refresh_files_btn.click(
            refresh_files,
            outputs=[files_display]
        )
        
        # Initialize displays
        demo.load(
            fn=lambda: (refresh_files(), update_stats(), get_exec_history()),
            outputs=[files_display, stats_display, exec_history]
        )
    
    return demo

# Create and launch the application
if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True,
        show_api=True
    )