#include <string>
#include <cstdio>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <thread>
#include <atomic>
#include <mutex>
#include <dirent.h>
#include <vector>
#include <chrono>
#include <random>

static std::mutex g_ocdt_mutex;
static std::string g_ocdt_result;
static std::atomic<bool> g_ocdt_done{false};

static bool CheckMagic(int fd) {
    unsigned char buf[4] = {0};
    ssize_t n = pread(fd, buf, 4, 0);
    if (n != 4) return false;
    return buf[0] == 0x54 && buf[1] == 0x44 && buf[2] == 0x43 && buf[3] == 0x4F;
}

static bool IsLargeEnough(int fd) {
    struct stat st;
    if (fstat(fd, &st) != 0) return false;
    if (S_ISBLK(st.st_mode)) {
        off_t sz = lseek(fd, 0, SEEK_END);
        if (sz < 0) return false;
        return sz >= 65536;
    }
    return st.st_size >= 65536;
}

static std::string RandomName(size_t len) {
    static const char charset[] =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, sizeof(charset) - 2);
    std::string s;
    s.reserve(len);
    for (size_t i = 0; i < len; ++i) s.push_back(charset[dis(gen)]);
    return s;
}

static bool CopyPartition(int src_fd) {
    std::string dir = "/data/local/tmp/" + RandomName(8);
    if (mkdir(dir.c_str(), 0755) != 0 && errno != EEXIST) {
        return false;
    }
    std::string dst_path = dir + "/ocdt.img";
    int dst_fd = open(dst_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (dst_fd < 0) {
        return false;
    }

    char buf[65536];
    off_t offset = 0;
    for (;;) {
        ssize_t n = pread(src_fd, buf, sizeof(buf), offset);
        if (n < 0) {
            if (errno == EINTR) continue;
            close(dst_fd);
            return false;
        }
        if (n == 0) break;
        ssize_t written = 0;
        while (written < n) {
            ssize_t w = write(dst_fd, buf + written, n - written);
            if (w < 0) {
                if (errno == EINTR) continue;
                int err = errno;
                close(dst_fd);
                (void)err;
                return false;
            }
            written += w;
        }
        offset += n;
    }
    close(dst_fd);
    return true;
}

static std::vector<std::string> CollectPartitions() {
    std::vector<std::string> paths;
    const char* dirs[] = {"/dev/block", "/dev/block/by-name"};
    for (const char* d : dirs) {
        DIR* dp = opendir(d);
        if (!dp) continue;
        struct dirent* ent;
        while ((ent = readdir(dp)) != nullptr) {
            if (ent->d_name[0] == '.') continue;
            std::string full = std::string(d) + "/" + ent->d_name;
            struct stat st;
            if (stat(full.c_str(), &st) == 0) {
                if (S_ISBLK(st.st_mode) || S_ISLNK(st.st_mode) || S_ISREG(st.st_mode)) {
                    paths.push_back(full);
                }
            } else {
                paths.push_back(full);
            }
        }
        closedir(dp);
    }
    return paths;
}

void StartExtractOCDT() {
    g_ocdt_done = false;
    {
        std::lock_guard<std::mutex> lock(g_ocdt_mutex);
        g_ocdt_result.clear();
    }
    std::thread([]() {
        auto start = std::chrono::steady_clock::now();
        std::string result;
        bool found = false;
        int found_fd = -1;
        bool any_partition_listed = false;

        const std::string ocdt_path = "/dev/block/by-name/ocdt";
        int fd = open(ocdt_path.c_str(), O_RDONLY);
        if (fd >= 0) {
            any_partition_listed = true;
            if (CheckMagic(fd) && IsLargeEnough(fd)) {
                found = true;
                found_fd = fd;
            } else {
                close(fd);
            }
        }

        if (!found) {
            auto parts = CollectPartitions();
            if (!parts.empty()) {
                any_partition_listed = true;
            }
            for (const auto& p : parts) {
                auto now = std::chrono::steady_clock::now();
                if (std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count() > 3000) {
                    break;
                }
                if (p == ocdt_path) continue;
                int f = open(p.c_str(), O_RDONLY);
                if (f < 0) continue;
                if (CheckMagic(f) && IsLargeEnough(f)) {
                    found = true;
                    found_fd = f;
                    break;
                }
                close(f);
            }
        }

        if (found) {
            bool ok = CopyPartition(found_fd);
            close(found_fd);
            result = ok ? "OCDT分区提取成功" : "OCDT分区提取失败：创建镜像文件失败";
        } else if (!any_partition_listed) {
            result = "OCDT分区提取失败：打开快设备失败";
        } else {
            result = "OCDT分区提取失败";
        }

        {
            std::lock_guard<std::mutex> lock(g_ocdt_mutex);
            g_ocdt_result = result;
        }
        g_ocdt_done = true;
    }).detach();
}

void PrintOCDTResult() {
    while (!g_ocdt_done) {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    std::lock_guard<std::mutex> lock(g_ocdt_mutex);
    printf("%s\n", g_ocdt_result.c_str());
    fflush(stdout);
}