import fs from 'node:fs'
import path from 'node:path'
import { Args, Command, Flags } from '@oclif/core'
import { FastStoreSandboxAnalyzer } from '@vtex/fsp-analyzer'
import { glob } from 'glob'

export class Analyze extends Command {
  static description =
    'Run static analysis on modules to ensure they follow FastStore Platform security guidelines'

  static examples = ['<%= config.bin %> <%= command.id %> --account=myStore']

  static flags = {
    path: Flags.string({
      description: 'Path to analyze (supports glob patterns)',
      default: 'src/**/*.{js,jsx,ts,tsx}',
    }),
    verbose: Flags.boolean({
      description: 'Show detailed information about each violation',
      default: false,
      char: 'v',
    }),
  }

  static args = {
    account: Args.string({
      required: true,
      description: 'Store account to analyze',
    }),
  }

  async run(): Promise<void> {
    const { flags, args } = await this.parse(Analyze)

    this.log(`Running static analysis for ${args.account} 🔍`)

    const analyzer = new FastStoreSandboxAnalyzer()
    const filePattern = flags.path

    // Find all files matching the pattern
    const files = await glob(filePattern, { ignore: ['node_modules/**'] })

    if (files.length === 0) {
      this.error(`No files found matching pattern: ${filePattern}`)
    }

    // Process each file
    for (const file of files) {
      const filePath = path.resolve(file)
      const code = fs.readFileSync(filePath, 'utf-8')

      const result = analyzer.analyzeCode(code, file)

      const totalViolations = result.violations.length
      const totalWarnings = result.warnings.length

      this.logJson(result)

      if (totalViolations > 0 || totalWarnings > 0) {
        this.error(
          'We found some issues in your code. Please address them and try again.'
        )
      }

      this.log(`✅ All good! No issues found in ${file}.`)
    }
  }
}
