from flask import Flask, request
import webbrowser
import threading
import subprocess
import tempfile
import os
import sys
import io

app = Flask(__name__)

def open_browser():
    webbrowser.open_new_tab("http://127.0.0.1:5000/")

@app.route('/', methods=['GET', 'POST'])
def index():
    code = ""
    output = ""

    if request.method == 'POST':
        code = request.form.get('code', '')
        mode = request.form.get('mode', '')

        if mode == 'python':
            try:
                old_stdout = sys.stdout
                redirected_output = sys.stdout = io.StringIO()
                exec(code, {})
                output = redirected_output.getvalue()
                sys.stdout = old_stdout
            except Exception as e:
                output = f"Python Error: {e}"

        elif mode in ['c', 'cpp', 'c_run']:
            suffix = '.c' if mode in ['c', 'c_run'] else '.cpp'
            compiler = 'gcc' if suffix == '.c' else 'g++'
            with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as src:
                src.write(code.encode('utf-8'))
                src_path = src.name

            exe_path = src_path.replace(suffix, '')
            try:
                subprocess.check_output([compiler, src_path, '-o', exe_path], stderr=subprocess.STDOUT)
                result = subprocess.check_output([exe_path], stderr=subprocess.STDOUT).decode()
                output = result
            except subprocess.CalledProcessError as e:
                output = f"{mode.upper()} Error:\n" + e.output.decode()
            finally:
                os.remove(src_path)
                if os.path.exists(exe_path):
                    os.remove(exe_path)

    return f"""
    <html>
    <head>
        <title>Retro CRT Code Runner</title>
        <style>
            body {{
                background-color: #111;
                margin: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 55vh;
                font-family: 'Courier New', monospace;
            }}
            .computer {{
                width: 850px;
                height: 800px;
                background: #222;
                border-radius: 20px;
                border: 12px solid #333;
                box-shadow: 0 0 50px #0f0, inset 0 0 25px #0f0;
                display: flex;
                flex-direction: column;
                overflow: hidden;
                position: relative;
            }}
            .screen-frame {{
                flex: 1;
                margin: 20px;
                background: #010;
                border: 4px solid #0f0;
                border-radius: 10px;
                overflow: hidden;
                display: flex;
            }}
            .screen {{
                flex: 1;
                padding: 15px;
                color: #0f0;
                font-size: 42px;
                line-height: 1.3;
                white-space: pre-wrap;
                overflow-y: auto;
                background: radial-gradient(circle at center, #010 0%, #001100 100%);
                image-rendering: pixelated;
                outline: none;
                caret-color: #0f0;
                overflow-wrap: break-word;
            }}
            .screen::before {{
                content: "";
                position: absolute;
                top: 0; left: 0;
                width: 100%; height: 100%;
                background-image: linear-gradient(rgba(0,0,0,0.15) 50%, transparent 50%);
                background-size: 100% 4px;
                pointer-events: none;
            }}
            .output-frame {{
                height: 220px;
                margin: 0 20px 10px 20px;
                background: #010;
                border: 4px solid #0f0;
                border-radius: 10px;
                overflow: hidden;
                display: flex;
            }}
            .output {{
                flex: 1;
                padding: 10px;
                color: #0f0;
                font-size: 48px;
                line-height: 1.3;
                white-space: pre-wrap;
                overflow-y: auto;
                background: radial-gradient(circle at center, #010 0%, #001100 100%);
                image-rendering: pixelated;
                overflow-wrap: break-word;
            }}
            .buttons {{
                display: flex;
                justify-content: space-around;
                margin: 10px 20px;
            }}
            .run-button {{
                font-family: 'Courier New', monospace;
                font-weight: bold;
                width: 220px;
                font-size: 50px;
                padding: 8px 16px;
                background-color: #0f0;
                color: #010;
                border: none;
                border-radius: 4px;
                cursor: pointer;
            }}
            .run-button:hover {{
                background-color: #0c0;
            }}
        </style>
    </head>
    <body>
        <div class="computer">
            <div class="screen-frame">
                <textarea class="screen" id="screen" name="code">{code}</textarea>
            </div>
            <div class="output-frame">
                <div class="output" id="output">{output}</div>
            </div>
            <div class="buttons">
                <button class="run-button" onclick="runCode('c_run')">C</button>
                <button class="run-button" onclick="runCode('cpp')">C++</button>
                <button class="run-button" onclick="runCode('python')">Python</button>
            </div>
        </div>
        <form id="codeForm" method="POST" style="display:none;">
            <input type="hidden" name="mode" id="modeInput">
            <textarea name="code" id="formCode">{code}</textarea>
        </form>
        <script>
            const screen = document.getElementById('screen');
            const formCode = document.getElementById('formCode');
            const modeInput = document.getElementById('modeInput');

            function runCode(mode) {{
                modeInput.value = mode;
                formCode.value = screen.value;
                document.getElementById('codeForm').submit();
            }}
        </script>
    </body>
    </html>
    """

if __name__ == '__main__':
    threading.Timer(1, open_browser).start()
    app.run(debug=True)