// Planu — Coupling metric (SPEC-482)
// coupling = fan-in (files that import THIS file) + fan-out (files THIS file imports).
import { readFileSync } from 'node:fs';
/** Count the number of import statements in a file (fan-out). */
export function computeFanOut(filePath) {
    let source;
    try {
        source = readFileSync(filePath, 'utf8');
    }
    catch {
        return 0;
    }
    const matches = source.match(/^import\s+/gm);
    return matches !== null ? matches.length : 0;
}
/** Count how many files in the project import a given file (fan-in). */
export function computeFanIn(filePath, allFilePaths) {
    // Derive the base name without extension for matching import paths
    const normalized = filePath.replace(/\\/g, '/');
    const parts = normalized.split('/');
    // Try matching by base filename (without extension) as it appears in import strings
    const base = parts[parts.length - 1]?.replace(/\.[^.]+$/, '') ?? '';
    let count = 0;
    for (const fp of allFilePaths) {
        if (fp === filePath) {
            continue;
        }
        let source;
        try {
            source = readFileSync(fp, 'utf8');
        }
        catch {
            continue;
        }
        // Match patterns like: from './a.js', from '../foo/a.js', from './a'
        const importRe = /from\s+['"]([^'"]+)['"]/g;
        let m;
        importRe.lastIndex = 0;
        while ((m = importRe.exec(source)) !== null) {
            const importPath = m[1] ?? '';
            const importBase = importPath
                .split('/')
                .pop()
                ?.replace(/\.[^.]+$/, '') ?? '';
            if (importBase === base) {
                count++;
                break; // count once per file even if imported multiple times
            }
        }
    }
    return count;
}
/** Compute total coupling score for a file (fan-in + fan-out). */
export function computeCoupling(filePath, allFilePaths) {
    return computeFanIn(filePath, allFilePaths) + computeFanOut(filePath);
}
//# sourceMappingURL=coupling.js.map