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

const webTranspile = require('../lib/transpile')

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

function assertHtmlSource(absPath, cliName) {
  const e = path.extname(absPath).toLowerCase()
  if (e !== '.html' && e !== '.htm') {
    throw new Error(`${cliName} requires a .html or .htm source file (got ${e || 'no extension'})`)
  }
}

/**
 * HTML template libraries: copy only (no JSX codemod). Use `from-jsx` / `from-tsx` for React conversion.
 */
async function templateV2FromHtmlCommand(file, opts = {}) {
  const cliName = 'from-html'
  try {
    if (!file) throw new Error('file argument is required')
    const absInput = path.resolve(file)
    if (!fs.existsSync(absInput)) throw new Error(`File not found: ${file}`)
    assertHtmlSource(absInput, cliName)

    const ext = path.extname(absInput)
    const base = path.basename(absInput, ext)
    const defaultOut = path.join(path.dirname(absInput), `${base}.export${ext}`)
    const outPath = opts.out === '-' ? '-' : path.resolve(opts.out || defaultOut)

    const code = fs.readFileSync(absInput, 'utf8')
    const codeType = detectCodeType(absInput)

    if (opts.dryRun) {
      console.log(chalk.blue(`Would copy ${absInput} -> ${outPath === '-' ? '<stdout>' : outPath}`))
      return
    }

    if (outPath === '-') {
      process.stdout.write(code)
      console.log(chalk.green('\nDone (stdout).'))
      return
    }

    if (fs.existsSync(outPath) && path.resolve(outPath) === path.resolve(absInput)) {
      throw new Error(
        'Output would overwrite input; pass a different path with --out (e.g. --out ./Hero.copy.html)',
      )
    }

    fs.mkdirSync(path.dirname(outPath), { recursive: true })
    fs.writeFileSync(outPath, code, 'utf8')
    console.log(chalk.green(`Wrote ${outPath}`))

    if (opts.strict || opts.verify !== false) {
      try {
        void webTranspile(code, codeType, path.basename(outPath))
      } catch (e) {
        throw new Error(`Verify transpile failed: ${e.message}`)
      }
      if (opts.strict) {
        console.log(
          chalk.dim('Skipping ESLint for HTML (not ECMAScript); transpile check was a no-op.'),
        )
      }
    }

    console.log(
      chalk.dim(
        'Pure HTML copy for v2 template libraries. For React → $() templates use `from-jsx` / `from-tsx`.',
      ),
    )
    console.log(chalk.green('\nDone.'))
  } catch (error) {
    console.error(chalk.red(`\n${cliName} failed: ${error.message}`))
    process.exit(1)
  }
}

module.exports = templateV2FromHtmlCommand
