#pragma once

#include <QTextEdit>
#include <QProcess>
#include <QObject>
#include <QTemporaryDir>
#include <QThread>
#include <QMutex>
#include <QWaitCondition>

class PythonRunner : public QObject {
    Q_OBJECT

public:
    PythonRunner(QTextEdit* outputWidget, QObject* parent = nullptr);
    ~PythonRunner();

    bool runScript(const QString& scriptContent);
    void stopScript();

private slots:
    void onOutputAvailable();
    void onErrorAvailable();
    void onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus);
    void onVenvProcessFinished(int exitCode, QProcess::ExitStatus exitStatus);

signals:
    void scriptFinished(int code);
    void venvPreparationProgress(const QString& message);
    void venvPreparationFinished();

private:
    void prepareVenv();
    void installEismultiplexerPackage();
    QString getPythonExecutable();
    QString getVenvPath();
    QString getVenvPythonPath();

public:
    bool isVenvReady();

    QTextEdit* m_outputWidget;
    QProcess* m_process;
    QProcess* m_venvProcess;
    bool ready;
    QTemporaryDir dir;
    QMutex venvMutex;
    QWaitCondition venvCondition;
    bool venvPreparing;
};
