/**
 * validate-blazor command
 *
 * Validates Fluent UI Blazor patterns and icons in Razor files.
 *
 * Usage:
 *   morph-spec validate-blazor [path]
 *   morph-spec validate-blazor src/Components --verbose
 */

import { glob } from 'glob';
import { readFileSync, existsSync, statSync } from 'fs';
import { join, resolve } from 'path';
import chalk from 'chalk';
import ora from 'ora';

import {
  validateBlazorFile,
  formatIssues,
} from '../../lib/validators/blazor/blazor-validator.js';
import { countIssues } from '../../lib/validators/shared/index.js';

/**
 * Main command handler for validate-blazor.
 *
 * @param {string} [targetPath] - Path to validate (file or directory)
 * @param {Object} options - Command options
 * @param {boolean} [options.verbose] - Show detailed output
 * @param {boolean} [options.fix] - Auto-fix issues where possible
 */
export async function validateBlazorCommand(targetPath, options = {}) {
  const { verbose = false } = options;

  console.log('');
  console.log(
    chalk.cyan('\uD83D\uDD0D Validating Fluent UI Blazor patterns...')
  );
  console.log('');

  // Determine target path
  const basePath = targetPath ? resolve(targetPath) : process.cwd();

  if (!existsSync(basePath)) {
    console.log(chalk.red(`\u274C Path not found: ${basePath}`));
    process.exit(1);
  }

  const spinner = ora('Scanning for Razor files...').start();

  let files = [];

  try {
    const stats = statSync(basePath);

    if (stats.isFile()) {
      // Single file
      if (
        basePath.endsWith('.razor') ||
        basePath.endsWith('.razor.cs') ||
        basePath.endsWith('.cs')
      ) {
        files = [basePath];
      } else {
        spinner.fail('File must be .razor or .cs');
        process.exit(1);
      }
    } else {
      // Directory - find all Razor files
      const pattern = join(basePath, '**/*.{razor,razor.cs}');
      files = await glob(pattern, {
        ignore: ['**/node_modules/**', '**/bin/**', '**/obj/**'],
        windowsPathsNoEscape: true,
      });
    }

    spinner.succeed(`Found ${files.length} Razor file(s)`);
  } catch (error) {
    spinner.fail(`Error scanning files: ${error.message}`);
    process.exit(1);
  }

  if (files.length === 0) {
    console.log(chalk.yellow('\n\u26A0\uFE0F No Razor files found to validate'));
    return;
  }

  // Validate each file
  const allIssues = [];
  const fileResults = [];

  for (const file of files) {
    try {
      const content = readFileSync(file, 'utf-8');
      const issues = validateBlazorFile(content, file);

      if (issues.length > 0) {
        allIssues.push(...issues);
        fileResults.push({ file, issues });
      }
    } catch (error) {
      console.log(chalk.red(`\u274C Error reading ${file}: ${error.message}`));
    }
  }

  // Output results
  console.log('');

  if (allIssues.length === 0) {
    console.log(
      chalk.green('\u2705 No issues found! All patterns look correct.')
    );
    console.log('');
    return;
  }

  // Group and display issues
  if (verbose) {
    // Verbose: show all issues with details
    fileResults.forEach(({ file, issues }) => {
      console.log(chalk.white.bold(`\n${file}`));
      console.log(chalk.gray('-'.repeat(60)));
      console.log(formatIssues(issues));
    });
  } else {
    // Compact: just list issues
    allIssues.forEach((issue) => {
      const icon = issue.type === 'error' ? '\u274C' : '\u26A0\uFE0F';
      const location = issue.line ? `${issue.file}:${issue.line}` : issue.file;

      console.log(`${icon} ${issue.message}`);
      if (issue.suggestion) {
        console.log(chalk.gray(`   \u2192 ${issue.suggestion}`));
      }
      console.log(chalk.dim(`   ${location}`));
      console.log('');
    });
  }

  // Summary
  const { errors, warnings } = countIssues(allIssues);
  const summaryColor = errors > 0 ? chalk.red : chalk.yellow;

  console.log(chalk.gray('-'.repeat(60)));
  console.log(
    summaryColor(
      `\n${files.length} arquivo(s) validado(s) | ${errors} erro(s) | ${warnings} warning(s)\n`
    )
  );

  // Exit with error code if there are errors
  if (errors > 0) {
    process.exit(1);
  }
}

export default validateBlazorCommand;
