const fs = require('fs')
const path = require('path')
const chalk = require('chalk')

const webTranspile = require('../lib/transpile')
const { lint } = require('../lib/lint')

function detectCodeType(filePath) {
  const ext = path.extname(filePath).toLowerCase()
  const map = { '.js': 'js', '.jsx': 'jsx', '.ts': 'ts', '.tsx': 'tsx', '.html': 'html' }
  return map[ext] || 'jsx'
}

/** V2: validate pure JS/JSX (no $() preprocessing). */
async function templateValidateCommand(file, opts) {
  try {
    const abs = path.resolve(file)
    if (!fs.existsSync(abs)) throw new Error(`File not found: ${file}`)
    const code = fs.readFileSync(abs, 'utf8')
    const codeType = detectCodeType(abs)

    let hadError = false

    if (opts.lint !== false) {
      const lintResult = await lint(code, abs)
      if (lintResult.errorCount > 0) {
        hadError = true
        console.log(chalk.red(`\nLint errors (${lintResult.errorCount}):`))
        lintResult.issues
          .filter((i) => i.severity === 'error')
          .forEach((i) => console.log(chalk.red(`  Line ${i.line}: ${i.message}`)))
      }
      if (lintResult.warningCount > 0 && opts.quiet !== true) {
        console.log(chalk.yellow(`\nLint warnings (${lintResult.warningCount}):`))
        lintResult.issues
          .filter((i) => i.severity === 'warning')
          .forEach((i) => console.log(chalk.yellow(`  Line ${i.line}: ${i.message}`)))
      }
    }

    try {
      void webTranspile(code, codeType, path.basename(abs))
    } catch (e) {
      hadError = true
      console.log(chalk.red(`\nTranspile error: ${e.message}`))
    }

    if (hadError) {
      console.error(chalk.red('\nvalidate: FAILED'))
      process.exit(1)
    }
    console.log(chalk.green('\nvalidate: OK'))
  } catch (error) {
    console.error(chalk.red(`\nvalidate failed: ${error.message}`))
    process.exit(1)
  }
}

module.exports = templateValidateCommand
