import { readFile, writeFile, access } from 'node:fs/promises';
import { join } from 'node:path';
const ESLINT_CONFIG_FILES = [
    'eslint.config.js',
    'eslint.config.mjs',
    'eslint.config.cjs',
    '.eslintrc.js',
    '.eslintrc.cjs',
    '.eslintrc.json',
    '.eslintrc.yaml',
    '.eslintrc.yml',
    '.eslintrc',
];
const PRETTIER_CONFIG_FILES = [
    '.prettierrc',
    '.prettierrc.json',
    '.prettierrc.js',
    '.prettierrc.cjs',
    '.prettierrc.yaml',
    '.prettierrc.yml',
    'prettier.config.js',
    'prettier.config.cjs',
];
async function fileExists(filePath) {
    try {
        await access(filePath);
        return true;
    }
    catch {
        return false;
    }
}
async function anyFileExists(dir, names) {
    for (const name of names) {
        if (await fileExists(join(dir, name))) {
            return true;
        }
    }
    return false;
}
function getPackageManager(knowledge) {
    const pm = knowledge.packageManager ?? 'npm';
    if (pm === 'yarn') {
        return 'yarn';
    }
    if (pm === 'pnpm') {
        return 'pnpm';
    }
    if (pm === 'bun') {
        return 'bun';
    }
    return 'npm';
}
function pmAddDev(pm, pkg) {
    if (pm === 'yarn') {
        return `yarn add -D ${pkg}`;
    }
    if (pm === 'pnpm') {
        return `pnpm add -D ${pkg}`;
    }
    if (pm === 'bun') {
        return `bun add -d ${pkg}`;
    }
    return `npm install -D ${pkg}`;
}
function hasDevDep(packageJson, dep) {
    const devDeps = packageJson.devDependencies;
    if (typeof devDeps !== 'object' || devDeps === null) {
        return false;
    }
    return dep in devDeps;
}
function buildEslintConfig(framework) {
    const isNext = framework?.toLowerCase().includes('next') ?? false;
    const isReact = !isNext && (framework?.toLowerCase().includes('react') ?? false);
    if (isNext) {
        return `import nextPlugin from '@next/eslint-plugin-next';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  ...tseslint.configs.strictTypeChecked,
  {
    plugins: { '@next/next': nextPlugin },
    rules: {
      ...nextPlugin.configs.recommended.rules,
      ...nextPlugin.configs['core-web-vitals'].rules,
    },
  },
  {
    languageOptions: {
      parserOptions: { project: true, tsconfigRootDir: import.meta.dirname },
    },
  },
);
`;
    }
    if (isReact) {
        return `import reactPlugin from 'eslint-plugin-react';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  ...tseslint.configs.strictTypeChecked,
  {
    plugins: { react: reactPlugin },
    rules: {
      ...reactPlugin.configs.recommended.rules,
      'react/react-in-jsx-scope': 'off',
    },
    settings: { react: { version: 'detect' } },
  },
  {
    languageOptions: {
      parserOptions: { project: true, tsconfigRootDir: import.meta.dirname },
    },
  },
);
`;
    }
    // Node/Express or generic TypeScript
    return `import tseslint from 'typescript-eslint';

export default tseslint.config(
  ...tseslint.configs.strictTypeChecked,
  {
    languageOptions: {
      parserOptions: { project: true, tsconfigRootDir: import.meta.dirname },
    },
  },
);
`;
}
const PRETTIER_CONFIG = JSON.stringify({
    semi: true,
    singleQuote: true,
    tabWidth: 2,
    trailingComma: 'all',
    printWidth: 100,
}, null, 2) + '\n';
export async function scaffoldLintConfig(projectPath, knowledge) {
    const result = {
        eslintCreated: false,
        prettierCreated: false,
        suggestions: [],
    };
    const lang = knowledge.language.toLowerCase();
    const isJsTs = lang === 'typescript' || lang === 'javascript' || lang === 'unknown';
    if (!isJsTs) {
        // Python/Go/Rust — suggest language-specific linters, skip file generation
        if (lang === 'python') {
            result.suggestions.push('Use ruff or flake8 for Python linting.');
        }
        else if (lang === 'go') {
            result.suggestions.push('Use golangci-lint for Go linting.');
        }
        else if (lang === 'rust') {
            result.suggestions.push('Use clippy for Rust linting.');
        }
        return result;
    }
    // Read package.json for devDependencies check
    let packageJson = {};
    try {
        const raw = await readFile(join(projectPath, 'package.json'), 'utf-8');
        packageJson = JSON.parse(raw);
    }
    catch {
        /* no package.json — skip dep checks */
    }
    const pm = getPackageManager(knowledge);
    // ESLint scaffolding
    const eslintConfigExists = await anyFileExists(projectPath, ESLINT_CONFIG_FILES);
    if (!eslintConfigExists) {
        const eslintInstalled = hasDevDep(packageJson, 'eslint');
        if (!eslintInstalled) {
            result.suggestions.push(`Install ESLint: ${pmAddDev(pm, 'eslint typescript-eslint')}`);
        }
        else {
            const config = buildEslintConfig(knowledge.framework);
            await writeFile(join(projectPath, 'eslint.config.js'), config, 'utf-8');
            result.eslintCreated = true;
        }
    }
    // Prettier scaffolding
    const prettierConfigExists = await anyFileExists(projectPath, PRETTIER_CONFIG_FILES);
    if (!prettierConfigExists) {
        const prettierInstalled = hasDevDep(packageJson, 'prettier');
        if (!prettierInstalled) {
            result.suggestions.push(`Install Prettier: ${pmAddDev(pm, 'prettier')}`);
        }
        else {
            await writeFile(join(projectPath, '.prettierrc'), PRETTIER_CONFIG, 'utf-8');
            result.prettierCreated = true;
        }
    }
    return result;
}
//# sourceMappingURL=lint-scaffolder.js.map