import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { dirExists, fileExists } from '../../fs/io.js';
import { expandLocalPaths, matchesPathPattern } from './expand.js';
function matchesGitignoreLine(localPath, line) {
    // Normalize: strip leading `/` (root-relative marker) and trailing `/` (dir marker)
    const normalizedLine = line.replace(/^\//, '').replace(/\/+$/, '');
    const normalizedPath = localPath.replace(/\/+$/, '');
    // Exact match
    if (normalizedPath === normalizedLine)
        return true;
    // Glob match (for patterns containing *, ?, or [)
    if (/[*?[]/.test(normalizedLine)) {
        return matchesPathPattern(normalizedPath, normalizedLine);
    }
    return false;
}
async function isPathGitignored(repoRoot, localPath) {
    const gitignorePath = join(repoRoot, '.gitignore');
    try {
        const content = await readFile(gitignorePath, 'utf8');
        const lines = content
            .split('\n')
            .map((l) => l.trim())
            .filter((l) => l !== '' && !l.startsWith('#'));
        return lines.some((line) => matchesGitignoreLine(localPath, line));
    }
    catch {
        return false;
    }
}
export async function checkLocalPathsStatus(repoRoot, localPaths) {
    const results = [];
    const { resolved, missingGlobs } = await expandLocalPaths(repoRoot, localPaths);
    for (const pattern of missingGlobs) {
        const gitignored = await isPathGitignored(repoRoot, pattern);
        results.push({ path: pattern, exists: false, gitignored });
    }
    for (const localPath of resolved) {
        const absolutePath = join(repoRoot, localPath);
        const exists = (await dirExists(absolutePath)) || (await fileExists(absolutePath));
        const gitignored = await isPathGitignored(repoRoot, localPath);
        results.push({ path: localPath, exists, gitignored });
    }
    return results;
}
