from flask import Flask, request, redirect, url_for
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():
    search_query = request.args.get('search')
    if search_query:
        url = f"https://www.google.com/search?q={search_query}"
        threading.Thread(target=lambda: webbrowser.open_new_tab(url)).start()
        return redirect(url_for('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>Offline Code Runner</title>
        <style>
            body {{
                background-color: #000;
                color: lightgrey;
                font-family: monospace;
                padding: 20px;
            }}
            #search-form {{
                display: flex;
                align-items: center;
                margin-bottom: 20px;
            }}
            #search-input {{
                font-family: monospace;
                font-size: 42px;
                background-color: #000;
                color: #ffffff;
                border: 5px outset #444;
                padding: 10px 14px;
                flex-grow: 1;
                max-width: 640px;
            }}
            #search-button {{
                font-family: monospace;
                font-size: 45px;
                background-color: #000;
                color: #ffffff;
                border: 4px outset #a2a2a2;
                padding: 8px 20px;
                cursor: pointer;
                margin-left: 8px;
            }}
            #editor {{
                width: 100%;
                height: 540px;
                border: 6px outset #222;
                font-size: 44px;
                line-height: 1.2;
                background: #000;
                color: lightgrey;
                padding: 20px;
                box-sizing: border-box;
                resize: none;
            }}
            #output {{
                width: 100%;
                height: 5em;
                font-size: 39px;
                background-color: #111;
                border: 7px solid #555;
                overflow-x: auto;
                white-space: pre-wrap;
                margin-top: 10px;
                color: lightgreen;
                padding: 12px;
                box-sizing: border-box;
            }}
            #html_preview {{
                width: 100%;
                height: 500px;
                border: 5px solid black;
                background-color: white;
                margin-top: 10px;
            }}
            .button-row {{
                display: flex;
                gap: 10px;
                margin-bottom: 10px;
            }}
            button.code-btn {{
                font-family: monospace;
                font-weight: bold;
                font-size: 36px;
                padding: 10px 0;
                background-color: #333;
                color: beige;
                border: 5px outset white;
                cursor: pointer;
                flex: 1;
                min-width: 0;
            }}
        </style>
    </head>
    <body>
        <form id="search-form" method="GET" action="/">
            <input id="search-input" name="search" autocomplete="off" />
            <button id="search-button" type="submit">Search</button>
        </form>
        <form method="POST" id="code-form">
            <textarea id="editor" name="code" spellcheck="false">{code}</textarea><br>
            <div class="button-row">
                <button class="code-btn" type="button" onclick="runCode('c_run')">C &gt;</button>
                <button class="code-btn" type="button" onclick="runCode('cpp')">C++ &gt;</button>
                <button class="code-btn" type="button" onclick="runCode('python')">Python &gt;</button>
                <button class="code-btn" type="button" onclick="fileInput.click()">Open</button>
                <button class="code-btn" type="button" onclick="runHTML()">HTML &gt;</button>
                <input type="file" id="fileInput" style="display:none" />
            </div>
            <div class="button-row">
                <button class="code-btn" type="button" onclick="selectAll()">Select All</button>
                <button class="code-btn" type="button" onclick="copyText()">Copy</button>
                <button class="code-btn" type="button" onclick="pasteText()">Paste</button>
                <button class="code-btn" type="button" onclick="cutText()">Cut</button>
                <button class="code-btn" type="button" onclick="full_view()">Full HTML</button>
            </div>
            <textarea id="output" readonly>{output}</textarea>
            <iframe id="html_preview"></iframe>
        </form>
        <script>
            const editor = document.getElementById('editor');
            const bottom = document.getElementById('html_preview');
            const fileInput = document.getElementById('fileInput');
            fileInput.addEventListener('change', function() {{
                const f = this.files[0];
                if (!f) return;
                const reader = new FileReader();
                reader.onload = function(e) {{
                    editor.value = e.target.result;
                }};
                reader.readAsText(f);
            }});
            let allowUnload = false;
            window.addEventListener("beforeunload", function(e) {{
                if (!allowUnload) {{
                    e.preventDefault();
                    e.returnValue = "";
                }}
            }});
            function runCode(mode) {{
                allowUnload = true;
                const form = document.getElementById("code-form");
                const modeInput = document.createElement("input");
                modeInput.type = "hidden";
                modeInput.name = "mode";
                modeInput.value = mode;
                form.appendChild(modeInput);
                form.submit();
            }}
            function runHTML() {{
                bottom.srcdoc = editor.value;
            }}
            function selectAll() {{
                editor.select();
            }}
            function copyText() {{
                navigator.clipboard.writeText(editor.value);
            }}
            function pasteText() {{
                navigator.clipboard.readText().then(text => {{
                    const start = editor.selectionStart;
                    const end = editor.selectionEnd;
                    editor.value = editor.value.substring(0, start) + text + editor.value.substring(end);
                }});
            }}
            function cutText() {{
                navigator.clipboard.writeText(editor.value);
                editor.value = '';
            }}
            function full_view() {{
                const blob = new Blob([editor.value], {{ type: 'text/html' }});
                const url = URL.createObjectURL(blob);
                window.open(url, '_blank');
            }}
        </script>
    </body>
    </html>
    '''
if __name__ == '__main__':
    threading.Timer(1, open_browser).start()
    app.run(debug=True)