import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export function resolveDriverScript(scriptName) {
    const candidates = [
        path.resolve(__dirname, '../drivers', scriptName),
        path.resolve(__dirname, 'drivers', scriptName),
        path.resolve(__dirname, '../server/hal/drivers', scriptName),
        path.resolve(process.cwd(), 'server/hal/drivers', scriptName),
        path.resolve(process.cwd(), 'dist/hal/drivers', scriptName),
        path.resolve(process.cwd(), 'drivers', scriptName),
        path.resolve(process.cwd(), scriptName)
    ];
    for (const c of candidates) {
        if (fs.existsSync(c)) return c;
    }
    return path.resolve(__dirname, '../drivers', scriptName);
}

export function resolvePythonExecutable() {
    if (process.env.PYTHON_PATH && fs.existsSync(process.env.PYTHON_PATH)) {
        return process.env.PYTHON_PATH;
    }
    const isWin = process.platform === 'win32';
    const venvRel = isWin ? 'Scripts/python.exe' : 'bin/python3';
    const candidates = [
        path.resolve(process.cwd(), 'venv', venvRel),
        path.resolve(__dirname, '../drivers/venv', venvRel),
        path.resolve(__dirname, 'drivers/venv', venvRel),
        path.resolve(process.cwd(), 'server/hal/drivers/venv', venvRel)
    ];
    for (const c of candidates) {
        if (fs.existsSync(c)) return c;
    }
    return isWin ? 'python' : 'python3';
}
