// mods/vbbsDownloadCounter.js - Cru Jones
"use strict";

var detailedReportFile = system.data_dir + "download_report.txt";
var totalCountFile     = system.data_dir + "download_count.txt";

var maxRetries   = 5;
var retryDelayMS = 500;

// === File opening helper with retry ===
function openFileWithRetry(path, mode) {
    var file = new File(path);
    var attempts = 0;

    while (attempts < maxRetries) {
        if (file.open(mode)) return file;

        attempts++;
//        print("Retrying: " + path + " (Attempt " + attempts + ")");
        mswait(retryDelayMS);
    }

//    print("ERROR: Could not open file: " + path);
    return null;
}

// === Check if file was already updated today ===
function shouldRunToday(filepath) {
    var file = new File(filepath);

    // Run if file doesn't exist
    if (!file.exists) return true;

    var lastModified = file.date;
    var now = time();

    var lastDay = strftime("%Y-%m-%d", lastModified);
    var today   = strftime("%Y-%m-%d", now);

    if (lastDay === today) {
 //       print("Already ran today (based on file date).");
        return false;
    }

    return true;
}

// === Main report generator ===
function generateDownloadReport() {

    if (!shouldRunToday(detailedReportFile)) {
//        print("Skipping report generation.");
        return false;
    }

    var detailedFile = openFileWithRetry(detailedReportFile, "w");
    var countFile    = openFileWithRetry(totalCountFile, "w");

    if (!detailedFile || !countFile) return false;

    var totalDownloads = 0;

    for (var lib = 0; lib < file_area.lib_list.length; lib++) {
        var libObj = file_area.lib_list[lib];
        detailedFile.writeln("\nLibrary: " + libObj.description);

        for (var dir = 0; dir < libObj.dir_list.length; dir++) {
            var dirObj = libObj.dir_list[dir];
            var filebase = new FileBase(dirObj.code);
            var dirDownloads = 0;

            if (!filebase.open()) {
                detailedFile.writeln("  [!] Failed to open directory: " + dirObj.code);
                continue;
            }

            var files = filebase.get_list(filebase.first_file);

            for (var i = 0; i < files.length; i++) {
                dirDownloads += files[i].times_downloaded || 0;
            }

            filebase.close();

            detailedFile.writeln(
                format("  Directory: %-20s Downloads: %5d",
                dirObj.description, dirDownloads)
            );

            totalDownloads += dirDownloads;
        }
    }

    detailedFile.writeln("\n==============================================");
    detailedFile.writeln(format("TOTAL DOWNLOADS ACROSS ALL AREAS: %d", totalDownloads));
    detailedFile.writeln("==============================================");

    countFile.writeln(totalDownloads);

    detailedFile.close();
    countFile.close();

//    print("Report generated successfully.");
    return true;
}

// === Execute ===
generateDownloadReport();
//print("\nReports written to:");
//print("  " + detailedReportFile);
//print("  " + totalCountFile);

