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)

        elif mode == 'unix':
            cursor_line = int(request.form.get('cursor_line', 0))
            lines = code.split('\n')
            command = lines[cursor_line]
            try:
                result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode()
            except subprocess.CalledProcessError as e:
                result = e.output.decode()
            result = result.rstrip()
            lines.insert(cursor_line + 1, result)
            lines.insert(cursor_line + 2, "")
            code = '\n'.join(lines)
            output = ""

    return f"""
<html>
<head>
    <title>Ubuntu-style Computer Runner</title>
    <style>
        body {{
            background-color: #101020;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 54vh;
            font-family: 'Courier New', monospace;
        }}
        .computer {{
            width: 880px;
            height: 820px;
            background: #555555;
            border-radius: 20px;
            border: 6px solid #333333;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            box-shadow: 0 8px 30px rgba(0,0,0,0.4);
            padding: 20px;
        }}
        .screen-frame {{
            flex: 1;
            margin-bottom: 15px;
            background: #300a24;
            border: 4px solid #00ffff;
            border-radius: 12px;
            display: flex;
            overflow: hidden;
        }}
        .screen {{
            flex: 1;
            padding: 15px;
            color: #eeeeee;
            font-size: 42px;
            line-height: 1.3;
            white-space: pre-wrap;
            overflow-y: auto;
            background: #300a24;
            caret-color: #dd4814;
            overflow-wrap: break-word;
        }}
        .output-frame {{
            height: 220px;
            background: #1c0012;
            border: 4px solid #ffff10;
            border-radius: 12px;
            overflow: hidden;
            display: flex;
        }}
        .output {{
            flex: 1;
            padding: 15px;
            color: #eeeeee;
            font-size: 48px;
            line-height: 1.3;
            white-space: pre-wrap;
            overflow-y: auto;
            background: #1c0012;
            overflow-wrap: break-word;
        }}
        .buttons {{
            display: flex;
            justify-content: space-around;
            margin-top: 10px;
        }}
        .run-button {{
            font-family: 'Courier New', monospace;
            font-weight: bold;
            width: 200px;
            font-size: 46px;
            padding: 20px 24px;
            background-color: #000020;
            color: #ffffff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
        }}
        .run-button:hover {{
            background-color: #e35a2a;
        }}
    </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>
            <button class="run-button" onclick="runCode('unix')">UNIX</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>
        <input type="hidden" name="cursor_line" id="cursorLine">
    </form>
    <script>
        const screen = document.getElementById('screen');
        const formCode = document.getElementById('formCode');
        const modeInput = document.getElementById('modeInput');
        const cursorLine = document.getElementById('cursorLine');

        function runCode(mode) {{
            modeInput.value = mode;
            formCode.value = screen.value;

            if (mode === 'unix') {{
                const pos = screen.selectionStart;
                const before = screen.value.slice(0, pos);
                const line = before.split('\\n').length - 1;
                cursorLine.value = line;
            }}

            document.getElementById('codeForm').submit();
        }}

        window.onload = function () {{
            screen.focus();
            screen.selectionStart = screen.value.length;
            screen.selectionEnd = screen.value.length;
        }};
    </script>
</body>
</html>
"""

if __name__ == '__main__':
    threading.Timer(1, open_browser).start()
    app.run(debug=True)