import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';
import globals from 'globals';
import react from 'eslint-plugin-react';
import reactHooks from 'eslint-plugin-react-hooks';
import tfdsTailwindContract from '../rules/tfds-tailwind-contract.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

function loadContract() {
  const contractPath = path.join(__dirname, '../contract.json');
  return JSON.parse(fs.readFileSync(contractPath, 'utf8'));
}

/** @returns {import('eslint').Linter.Config[]} */
export function createTfdsFlatPreset() {
  const contract = loadContract();
  const allowedSpacingTokens = (contract.spacingTokens || []).map((x) => x.token);

  return [
    { ignores: ['dist/**', 'node_modules/**'] },
    {
      files: ['**/*.{js,jsx}'],
      languageOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module',
        globals: {
          ...globals.browser,
        },
        parserOptions: {
          ecmaFeatures: { jsx: true },
        },
      },
      plugins: {
        react,
        'react-hooks': reactHooks,
        tfds: { rules: { 'tailwind-contract': tfdsTailwindContract } },
      },
      settings: { react: { version: 'detect' } },
      rules: {
        ...js.configs.recommended.rules,
        ...react.configs.recommended.rules,
        ...reactHooks.configs.recommended.rules,
        'react/react-in-jsx-scope': 'off',
        'react/jsx-uses-react': 'off',
        'tfds/tailwind-contract': [
          'error',
          {
            importSources: contract.importSources,
            allowedSpacingTokens,
            lockedLocalNames: contract.lockedLocalNames || [],
          },
        ],
      },
    },
  ];
}
