#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) {
    while(1) {
        string s;
        getline(cin, s);
        int ls = s.length();

        bool isn = 1;
        upl(i, 0, ls - 1, 1) { // 判断是否为自然数
            if(!isdigit(s[i])) {
                isn = 0;
                break;
            }
        }

        if(isn) {
            if(s.length() > 9) {
                Print("输入不在给定范围内，请重新输入。");
                continue;
            }

            int ans = 0;
            for(char c : s)
                ans = ans * 10 + c - '0'; // 转换为自然数
            if(a.find(ans) != a.end()) // 判断是否在 a 内出现
                return ans;
            else {
                Print("输入不在给定范围内，请重新输入。");
                continue;
            }
        } else {
            Print("输入不是自然数，请重新输入。");
            continue;
        }
    }
    return Error; // 其实这句是冗余的
} // 安全读入一个在 a 内出现的自然数
string Read_File_Path(string wh) {
    while(1) {
        string ans;
        getline(cin, ans);
        if(!exists(ans)) {
            Print("路径无效，请重新输入。");
            continue;
        }
        if(!is_regular_file(ans)) {
            Print("路径指向的不是文件，请重新输入。");
            continue;
        }

        size_t pos = ans.find_last_of('.');
        if(pos == string::npos) {
            Print("路径指向的文件类型不正确，请重新输入。");
            continue;
        } // 避免无扩展名的文件使程序崩溃
        string ext = ans.substr(pos + 1);
        transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
        if(ext != wh) {
            Print("路径指向的文件类型不正确，请重新输入。");
            continue;
        }
        return ans;
    }
    return to_string(Error);
} // 安全读入一个 wh 类型的文件的路径
string Read_Path() {
    while(1) {
        string ans;
        getline(cin, ans);
        if(!exists(ans)) {
            Print("路径无效，请重新输入。");
            continue;
        }
        return ans;
    }
    return to_string(Error);
} // 安全读入一个的路径
string Change(string s) {
    return "\"" + s + "\"";
} // 将一个字符串用 "" 包裹
bool Isfile(string s) {
    return exists(s) && is_regular_file(s);
} //判断 s 是否是一个指向某文件的路径

int Main_Page() {
    cout << string(43, ' ') << "Light C++ IDE" << "\n";
    cout << string(100, '-') << "\n";
    Print("1. 编辑 C++ 文件");
    Print("2. 运行 C++ 程序");
    Print("3. 设置");
    Print("4. 保存信息并退出", 2);
    int ans = Read_Pint({1, 2, 3, 4});
    return ans;
} // 打印主页面

int Settings_Page() {
    cout << string(39, ' ') << "Light C++ IDE -- 设置" << "\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++ IDE");
    Print("版本：Alpha 1.1");
    Print("发布时间：2025/10/3", 2);
    system("pause");
} // 打印程序信息
void Set_COM_Path() {
    system("cls");
    Print("当前编译器路径：" + COM_PATH);
    Print("请输入新编译器路径：");
    COM_PATH = Read_File_Path("exe");
    Print("设置成功！", 2);
    system("pause");
} // 设置编译器路径
void Set_CON_Path() {
    system("cls");
    Print("当前 ConsolePauser 路径：" + CON_PATH);
    Print("请输入新 ConsolePauser 路径：");
    CON_PATH = Read_File_Path("exe");
    Print("设置成功！", 2);
    system("pause");
} // 设置 ConsolePauser 路径
void Set_COM_Settings() {
    system("cls");
    Print("当前编译选项：" + 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();
    }
} // 设置

#define Com do{Print("正在编译……"); if(system(t.c_str())) {Print("编译失败！", 2); system("pause"); return;} else Print("编译成功！");}while(0) // 编译
void Run() {
    system("cls");
    Print("请输入 C++ 文件的完整路径：");
    string fpath = Read_File_Path("cpp");
    int lf = fpath.length();
    string epath = fpath.substr(0, lf - 4) + ".exe";
    cout << "\n";
    // 以上安全读入了一个路径

    if(!Isfile(COM_PATH)) {
        Print("编译器路径无效！请重新设置。", 2);
        system("pause");
        return;
    }
    string t = Change(COM_PATH) + " " + COM_SETTINGS + (COM_SETTINGS.length() ? " " : "") + "-g -o " + Change(epath) + " " + Change(fpath);
    t = "cmd /c" + Change(t);
    if(!Isfile(epath)) {
        Print("未找到对应程序的 exe 文件，自动编译。");
        Com;
    } else {
        Print("是否需要编译？（0/1）");
        bool ncom = Read_Pint({0, 1});
        if(ncom == 0)
            Print("跳过编译。");
        else if(ncom == 1)
            Com;
    }
    cout << "\n";
    // 以上完成了编译

    Print("是否需要运行？（0/1）");
    bool nrun = Read_Pint({0, 1});
    if(!nrun)
        Print("跳过运行。");
    else if(nrun) {
        if(!Isfile(CON_PATH)) {
            Print("ConsolePauser 路径无效。即将直接启动程序。");
            string t = "start " + Change(fpath) + " " + Change(epath);
            system(t.c_str());
            Print("启动成功！");
        } else {
            Print("正在通过 ConsolePauser 启动程序……");
            string t = "start \"\" " + Change(CON_PATH) + " " + Change(epath);
            system(t.c_str());
            Print("启动成功！");
        }
    }
    cout << "\n";
    // 以上完成了运行

    system("pause");
} // 运行代码
#undef Com

int Edit_Page() {
    cout << string(35, ' ') << "Light C++ IDE -- 编辑 C++ 文件" << "\n";
    cout << string(100, '-') << "\n";
    Print("1. 新建 C++ 文件");
    Print("2. 打开已有 C++ 文件");
    Print("3. 返回", 2);
    int ans = Read_Pint({1, 2, 3});
    return ans;
} // 编辑界面
void New_File() {
    system("cls");
    Print("请输入想要创建的文件的完整目录：");
    string fpath = Read_Path();

    Print("请输入想要创建的文件名（不含扩展名）：");
    string file;
    getline(cin, file);
    cout << "\n";

    string File = fpath + "\\" + file + ".cpp";
    if(Isfile(File)) {
        Print("文件已存在。", 2);
        system("pause");
        return;
    }

    ofstream fout(fpath + "\\" + file + ".cpp");
    Print("创建成功！", 2);
    system("pause");
} // 新建 C++ 文件
void Open_File() {
    system("cls");
    Print("请输入想要打开的文件的完整目录：");
    string fpath = Read_File_Path("cpp");
    cout << "\n";

    cout << "打开成功！请在弹出的窗口内编写代码，编写完成后保存。" << "\n\n";
    string t = "notepad.exe " + Change(fpath);
    system(t.c_str());
    system("pause");
} // 打开 C++ 文件
void Edit() {
    while(1) {
        system("cls");
        int op = Edit_Page();
        if(op == 3)
            return;
        else if(op == 1)
            New_File();
        else if(op == 2)
            Open_File();
    }
} // 编辑代码

signed main() {
    Init();

    while(1) {
        system("cls");
        int op = Main_Page();
        if(op == 4) {
            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 == 3)
            Settings();
        else if(op == 2)
            Run();
        else if(op == 1)
            Edit();
    }
	return 0;
}