import fs from 'fs';
import path from 'path';
import { dialog, app } from 'electron';

// The pnpm Force
// Watches for package-lock.json or yarn.lock and warns the user.

export function startEnforcement(projectPath: string) {
    // We can use fs.watch, but strictly we might want to watch the specific directory
    // where the user is working.
    // For this app, maybe we watch the projects user adds?
    // Or do we implement a global watcher? The PRD implies "actively monitor".
    // Monitoring the entire filesystem is expensive. 
    // We'll assume we monitor specific "Active Projects" added to the app.

    // Implementation note: This function would be called for each watched project.

    const watcher = fs.watch(projectPath, (eventType, filename) => {
        if (filename === 'package-lock.json' || filename === 'yarn.lock') {
            const lockFile = path.join(projectPath, filename);
            if (fs.existsSync(lockFile)) {
                handleViolation(lockFile);
            }
        }
    });

    return watcher;
}

function handleViolation(lockFile: string) {
    dialog.showMessageBox({
        type: 'warning',
        title: 'The pnpm Force',
        message: `Illegal lockfile detected: ${path.basename(lockFile)}`,
        detail: 'You must use pnpm! Do you want to convert now?',
        buttons: ['Convert to pnpm', 'Delete Lockfile', 'Ignore'],
        defaultId: 0
    }).then(result => {
        if (result.response === 0) {
            // Run conversion
        } else if (result.response === 1) {
            fs.unlinkSync(lockFile);
        }
    });
}
