#include <bits/stdc++.h>
#include <filesystem>
#include <windows.h>
using namespace std;
using namespace filesystem;
#define upl(i, s, t, d) for(int i = (s); i <= (t); i += (d))
#define dol(i, s, t, d) for(int i = (s); i >= (t); i -= (d))

const int Error = 114514; // 错误反馈
const string SETTINGS = "runner_data.sg"; // 设置的文件
string COM_PATH, CON_PATH, COM_SETTINGS; // 编译器路径、ConsolePauser 路径、编译选项

void Wait(double a) {
    this_thread::sleep_for(chrono::microseconds((int)(a * 1000000)));
} // 暂停 a 秒
void Print(string s, int nrow = 1) {
    int ls = s.length();
    upl(i, 0, ls - 1, 1) {
        cout << s[i];
        Wait(0.001);
    }
    cout << string(nrow, '\n');
} // 慢速输出 s 和 nrow 个换行 
void Init() {
    SetConsoleOutputCP(CP_UTF8);
    SetConsoleCP(CP_UTF8); // 设置编码，防止乱码
    system("title Runner"); // 设置标题
    ifstream fin(SETTINGS);
    if(exists(SETTINGS) && is_regular_file(SETTINGS)) {
        getline(fin, COM_PATH);
        getline(fin, CON_PATH);
        getline(fin, COM_SETTINGS);
    } // 读入编译器路径、ConsolePauser 路径、编译选项
} // 初始化
int Read_pint(unordered_set<int> a) {
    for(; ; Print("输入不合法，请重新输入。")) {
        string s;
        getline(cin, s);
        int ls = s.length();

        if(s.length() > 9) // 避免溢出
            continue;

        bool isn = 1;
        upl(i, 0, ls - 1, 1) { // 判断是否为正整数
            if(!isdigit(s[i])) {
                isn = 0;
                break;
            }
        }

        if(isn) {
            int ans = 0;
            for(char c : s)
                ans = ans * 10 + c - '0'; // 转换为正整数
            if(a.find(ans) != a.end()) // 判断是否在 a 内出现
                return ans;
        }
    }
    return Error; // 其实这句是冗余的
} // 安全读入一个在 a 内出现的的正整数

int Main_page() {
    cout << string(43, ' ') << "C++ 代码运行器" << "\n";
    cout << string(100, '-') << "\n";
    Print("1. 运行代码");
    Print("2. 设置");
    Print("3. 保存并退出", 2);
    int ans = Read_pint({1, 2, 3});
    return ans;
} // 打印主页面

int Settings_page() {
    cout << string(39, ' ') << "C++ 代码运行器 -- 设置" << "\n";
    cout << string(100, '-') << "\n";
    Print("1. 修改编译器（g++.exe）路径");
    Print("2. 修改 ConsolePauser 路径");
    Print("3. 修改编译选项");
    Print("4. 程序信息");
    Print("5. 返回", 2);
    int ans = Read_pint({1, 2, 3, 4, 5});
    return ans;
} // 打印设置界面
void Print_message() {
    system("cls");
    Print("作者：___Segment___（https://www.luogu.com.cn/798795）");
    Print("介绍：超轻量 C++ 代码运行器");
    Print("版本：Alpha 1.0");
    Print("发布时间：2025/10/3", 2);
    system("pause");
} // 打印程序信息
void Set_com_path() {
    system("cls");
    Print("当前编译器路径：" + (COM_PATH.length() ? COM_PATH : "<空>"));
    Print("请输入新编译器路径：");
    getline(cin, COM_PATH);
    Print("设置成功！", 2);
    system("pause");
} // 设置编译器路径
void Set_con_path() {
    system("cls");
    Print("当前 ConsolePauser 路径：" + (CON_PATH.length() ? CON_PATH : "<空>"));
    Print("请输入新 ConsolePauser 路径：");
    getline(cin, CON_PATH);
    Print("设置成功！", 2);
    system("pause");
} // 设置 ConsolePauser 路径
void Set_com_settings() {
    system("cls");
    Print("当前编译选项：" + (COM_SETTINGS.length() ? COM_SETTINGS : "<空>"));
    Print("请输入新编译选项：");
    getline(cin, COM_SETTINGS);
    Print("设置成功！", 2);
    system("pause");
} // 设置编译选项
void Settings() {
    while(1) {
        system("cls");
        int op = Settings_page();
        if(op == 5)
            return;
        else if(op == 4)
            Print_message();
        else if(op == 1)
            Set_com_path();
        else if(op == 2)
            Set_con_path();
        else if(op == 3)
            Set_com_settings();
    }
} // 设置

void Run() {
    system("cls");
    Print("请输入 C++ 文件的完整路径：");
    string fpath;
    for(; ; Print("路径无效或文件不合法！请重新输入。")) {
        getline(cin, fpath);
        if (fpath.length() < 4) continue;
        string ext = fpath.substr(fpath.find_last_of('.') + 1);
        transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
        if(exists(fpath) && is_regular_file(fpath) && ext == "cpp")
            break;
    }
    int lf = fpath.length();
    const string epath = fpath.substr(0, lf - 4) + ".exe";
    cout << "\n";
    // 以上安全读入了一个路径

    if(!exists(COM_PATH) || !is_regular_file(COM_PATH)) {
        Print("编译器路径无效！请重新设置。", 2);
        system("pause");
        return;
    }
    if(!exists(epath) || !is_regular_file(epath)) {
        Print("未找到对应程序的 exe 文件，自动为你编译。");
        Print("正在编译……");
        string t = "\"" + COM_PATH + "\" " + COM_SETTINGS + " -g -o \"" + epath + "\" \"" + fpath + "\"";
        t = "cmd /c \"" + t + "\"";
        if(system(t.c_str())) {
            Print("编译失败！", 2);
            system("pause");
            return;
        } else {
            Print("编译成功！");
        }
    } else {
        Print("是否需要编译？（0/1）");
        bool ncom = Read_pint({0, 1});
        if(ncom == 0) {
            Print("跳过编译。");
        } else if(ncom == 1) {
            Print("正在编译……");
            string t = "\"" + COM_PATH + "\" " + COM_SETTINGS + " -g -o \"" + epath + "\" \"" + fpath + "\"";
            t = "cmd /c \"" + t + "\"";
            if(system(t.c_str())) {
                Print("编译失败！", 2);
                system("pause");
                return;
            } else {
                Print("编译成功！");
            }
        }
    }
    cout << "\n";
    // 以上完成了编译

    Print("是否需要运行？（0/1）");
    bool nrun = Read_pint({0, 1});
    if(!nrun) {
        Print("跳过运行。");
    } else if(nrun) {
        if(!exists(CON_PATH) || !is_regular_file(CON_PATH)) {
            Print("ConsolePauser 路径无效。即将直接启动程序。");
            string t = "start \"" + fpath + "\" \"" + epath + "\"";
            system(t.c_str());
            Print("启动成功！");
        } else {
            Print("正在通过 ConsolePauser 启动程序……");
            string t = "start \"\" " + CON_PATH + " \"" + epath + "\"";
            system(t.c_str());
            Print("启动成功！");
        }
    }
    cout << "\n";
    // 以上完成了运行

    system("pause");
} // 运行代码

signed main() {
    Init();

    while(1) {
        system("cls");
        int op = Main_page();
        if(op == 3) {
            system("cls");
            remove(SETTINGS);
            ofstream fout(SETTINGS);
            fout << COM_PATH << "\n" << CON_PATH << "\n" << COM_SETTINGS;
            fout.close();
            SetFileAttributesA(SETTINGS.c_str(), FILE_ATTRIBUTE_HIDDEN);
            Print("将在 3s 内退出……");
            Wait(2.5);
            break;
        } else if(op == 2)
            Settings();
        else if(op == 1)
            Run();
    }
	return 0;
}