/**
 * analyze-blazor-concurrency command
 *
 * Analyzes Blazor Server code for DbContext concurrency issues.
 *
 * Usage:
 *   morph-spec analyze-blazor-concurrency [path]
 *   morph-spec analyze-blazor-concurrency src/Services --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 {
  analyzeConcurrency,
} from '../../lib/validators/blazor/blazor-concurrency-analyzer.js';
import { countIssues } from '../../lib/validators/shared/index.js';

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

  console.log('');
  console.log(
    chalk.cyan('\uD83D\uDD0D Analisando concorrencia DbContext em Blazor Server...')
  );
  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 C# files...').start();

  let files = [];

  try {
    const stats = statSync(basePath);

    if (stats.isFile()) {
      if (basePath.endsWith('.cs')) {
        files = [basePath];
      } else {
        spinner.fail('File must be .cs');
        process.exit(1);
      }
    } else {
      // Find all C# files (services, repositories, handlers)
      const pattern = join(basePath, '**/*.cs');
      files = await glob(pattern, {
        ignore: [
          '**/node_modules/**',
          '**/bin/**',
          '**/obj/**',
          '**/Migrations/**',
        ],
        windowsPathsNoEscape: true,
      });
    }

    spinner.succeed(`Found ${files.length} C# 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 C# files found to analyze'));
    return;
  }

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

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

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

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

  if (allIssues.length === 0) {
    console.log(
      chalk.green(
        '\u2705 Nenhum problema de concorrencia detectado!'
      )
    );
    console.log(
      chalk.gray(
        '   Dica: Certifique-se de usar IDbContextFactory para operacoes background.'
      )
    );
    console.log('');
    return;
  }

  // Display issues
  if (verbose) {
    fileResults.forEach(({ file, issues }) => {
      console.log(chalk.white.bold(`\n${file}`));
      console.log(chalk.gray('-'.repeat(60)));

      issues.forEach((issue) => {
        const icon =
          issue.type === 'error'
            ? '\u274C'
            : issue.type === 'warning'
            ? '\u26A0\uFE0F'
            : '\u2139\uFE0F';

        console.log(`${icon} ${issue.message}`);
        if (issue.suggestion) {
          console.log(chalk.gray(`   \u2192 ${issue.suggestion}`));
        }
        if (issue.line) {
          console.log(chalk.dim(`   Linha: ${issue.line}`));
        }
        if (issue.code) {
          console.log(chalk.dim(`   Codigo: ${issue.code}`));
        }
        console.log('');
      });
    });
  } else {
    allIssues.forEach((issue) => {
      const icon =
        issue.type === 'error'
          ? '\u274C'
          : issue.type === 'warning'
          ? '\u26A0\uFE0F'
          : '\u2139\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, infos } = countIssues(allIssues);
  const summaryColor = errors > 0 ? chalk.red : chalk.yellow;

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

  // Recommendation
  if (errors > 0) {
    console.log(
      chalk.cyan(
        '\uD83D\uDCD6 Consulte: framework/standards/backend/database/ef-core.md para padroes corretos'
      )
    );
    console.log('');
    process.exit(1);
  }
}

export default analyzeBlazorConcurrencyCommand;
