import { copyFileSync, existsSync, mkdirSync, readdirSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
/**
 * Resolve the absolute path to a provider's template directory.
 * Templates live in src/templates/ai/{provider}/ (dev) or dist/templates/ai/{provider}/ (prod).
 * __dirname is src/ai/domain or dist/ai/domain → go up 2 levels to src/ or dist/.
 */
function getTemplatesDir(providerName) {
    return join(__dirname, '..', '..', 'templates', 'ai', providerName);
}
function scanFiles(dir, baseDir) {
    const results = [];
    if (!existsSync(dir))
        return results;
    const entries = readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
        const fullPath = join(dir, entry.name);
        if (entry.isDirectory()) {
            results.push(...scanFiles(fullPath, baseDir));
        }
        else if (entry.isFile()) {
            results.push(relative(baseDir, fullPath));
        }
    }
    return results;
}
/**
 * Copy config files from templates to the target directory.
 * Never overwrites — only copies files that do NOT already exist.
 */
export function copyConfigFiles(providerName, targetDir, dryRun) {
    const templatesDir = getTemplatesDir(providerName);
    if (!existsSync(templatesDir))
        return [];
    const files = scanFiles(templatesDir, templatesDir);
    const messages = [];
    for (const relPath of files) {
        const destPath = join(targetDir, relPath);
        if (existsSync(destPath)) {
            messages.push(`[skip] ${relPath} (already exists)`);
            continue;
        }
        if (dryRun) {
            messages.push(`[dry-run] ${relPath}`);
            continue;
        }
        mkdirSync(dirname(destPath), { recursive: true });
        copyFileSync(join(templatesDir, relPath), destPath);
        messages.push(relPath);
    }
    return messages;
}
