/**
 * Install git / Husky hooks for local Samplebeacon gates (Community tier).
 */

const fs = require('fs');
const path = require('path');

const HOOK_TYPES = new Set(['pre-commit', 'pre-push']);

function buildHookScript(type, { failOn = 'high', withJest = false } = {}) {
    const scanArgs = [
        'scan',
        '--gate',
        `--fail-on ${failOn}`
    ];
    if (withJest || type === 'pre-push') {
        scanArgs.push('--with-jest');
    }

    const cmd = `npx samplebeacon ${scanArgs.join(' ')}`;

    return `#!/usr/bin/env sh
# Samplebeacon ${type} — Community tier local gate
# https://www.npmjs.com/package/samplebeacon
set -e
echo "Samplebeacon ${type}..."
${cmd}
echo "Samplebeacon ${type} passed"
`;
}

function resolveHookTarget(root, type, preferHusky) {
    const huskyDir = path.join(root, '.husky');
    const gitHooksDir = path.join(root, '.git', 'hooks');

    if (preferHusky || fs.existsSync(huskyDir)) {
        return { hookPath: path.join(huskyDir, type), kind: 'husky' };
    }
    if (fs.existsSync(gitHooksDir)) {
        return { hookPath: path.join(gitHooksDir, type), kind: 'git' };
    }
    return {
        hookPath: path.join(root, '.samplebeacon', 'hooks', type),
        kind: 'manual'
    };
}

function installSamplebeaconHook(root, options = {}) {
    const projectRoot = path.resolve(root || process.cwd());
    const type = options.type || 'pre-commit';
    if (!HOOK_TYPES.has(type)) {
        throw new Error(`Invalid hook type "${type}" — use pre-commit or pre-push`);
    }

    const failOn = options.failOn || 'high';
    const withJest = Boolean(options.withJest);
    const preferHusky = Boolean(options.preferHusky);
    const script = buildHookScript(type, { failOn, withJest });
    const { hookPath, kind } = resolveHookTarget(projectRoot, type, preferHusky);

    fs.mkdirSync(path.dirname(hookPath), { recursive: true });
    fs.writeFileSync(hookPath, script, { encoding: 'utf8', mode: 0o755 });

    return {
        hookPath,
        kind,
        type,
        manual: kind === 'manual'
    };
}

module.exports = {
    HOOK_TYPES,
    buildHookScript,
    installSamplebeaconHook
};
