#include "PythonConsole.h"
#include <imgui.h>
#include <SDL2/SDL.h>
#include <iostream>

PythonConsole::PythonConsole()
{
    AddLog("=== kariokaEngine Python Console ===");
    AddLog("Type Python code and press ENTER");
    AddLog("Use karioka.engine(), karioka.reload(), etc");
    AddLog("Press ~ to toggle this console");
}

void PythonConsole::Toggle()
{
    showConsole = !showConsole;
    if (showConsole)
    {
        reclaimFocus = true;
    }
}

void PythonConsole::AddLog(const std::string& message)
{
    logLines.push_back(message);
    scrollToBottom = true;
}

void PythonConsole::ExecuteCommand(const std::string& command)
{
    if (command.empty()) { return; }
    
    history.push_back(command);
    historyPos = -1;
    
    AddLog("> " + command);
    
    // Execute via PythonEngine
    try
    {
        PythonEngine::Get().Exec(command);
    }
    catch (...)
    {
        AddLog("[Error] Failed to execute command");
    }
}

void PythonConsole::Render()
{
    if (!showConsole) { return; }
    
    ImGui::SetNextWindowSize(ImVec2(800, 500), ImGuiCond_FirstUseEver);
    ImGui::SetNextWindowPos(ImVec2(100, 100), ImGuiCond_FirstUseEver);
    
    if (ImGui::Begin("Python Console (~)", &showConsole, ImGuiWindowFlags_NoCollapse))
    {
        // Log area
        ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetFrameHeightWithSpacing() * 2), true);
        for (const auto& line : logLines)
        {
            ImGui::TextUnformatted(line.c_str());
        }
        if (scrollToBottom)
        {
            ImGui::SetScrollHereY(1.0f);
            scrollToBottom = false;
        }
        ImGui::EndChild();
        
        // Command Input
        ImGui::Separator();
        bool reclaimFocus = false;
        if (ImGui::InputText("##Input", inputBuffer, IM_ARRAYSIZE(inputBuffer),
                             ImGuiInputTextFlags_EnterReturnsTrue))
        {
            std::string cmd = inputBuffer;
            ExecuteCommand(cmd);
            inputBuffer[0] = '\0';
            reclaimFocus = true;
        }
        
        // Autofocus when window becomes active
        //ImGui::SetItemDefaultFocus();
        if (reclaimFocus)
        {
            ImGui::SetKeyboardFocusHere(-1);
            reclaimFocus = false;
        }
        
        ImGui::End();
    }
}