import { createHash } from 'node:crypto'
import { mkdir, mkdtemp, readFile, writeFile, chmod, rename } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { spawnSync } from 'node:child_process'

export const version = '0.4.0'
const integrity = 'i+veX7/V57RpmAmJeuji+zgagzBW0Py1usJGDmEuv/ruVMZbF9rzA/O7zvuyhyPQJoQwSF/Y6/ah1TtCgGirXg=='
const marker = '// Jev AI jevgrep launcher v1'

export function adaptCli(source) {
  const start = '  providers = {\n'
  const end = '\n  };\n});'
  const a = source.indexOf(start)
  const b = source.indexOf(end, a)
  if (a < 0 || b < 0 || source.indexOf(start, a + 1) !== -1 || !source.slice(a, b).includes('https://api.typesafe.ai/v1')) {
    throw new Error('Unexpected upstream provider table. No adapter was installed.')
  }
  // Keep the TypeSafe wire protocol; offer only this site so its key cannot be
  // accidentally saved for another provider. Everything else stays upstream.
  return source.slice(0, a) + '  providers = {\n    typesafe: {\n      label: "Jev AI (jev-ai.pro)",\n      baseURL: "https://jev-ai.pro/api/v1",\n      model: "jev-latest"\n    }' + source.slice(b)
}

function run(command, args, options = {}) {
  const result = spawnSync(command, args, { stdio: 'inherit', ...options })
  if (result.error || result.status !== 0) throw new Error(`${command} failed. ${result.error?.message || 'See the output above.'}`)
}

export async function install() {
  if (Number(process.versions.node.split('.')[0]) < 22 || !['darwin', 'linux'].includes(process.platform)) {
    throw new Error('Node.js 22+ on macOS or Linux is required.')
  }
  const bin = join(homedir(), '.local/bin')
  const launcher = join(bin, 'jg')
  try {
    if (!(await readFile(launcher, 'utf8')).includes(marker)) throw new Error(`${launcher} already exists. Move it before installing this adapter.`)
  } catch (error) { if (error.code !== 'ENOENT') throw error }
  run('npm', ['--version'])
  const base = join(homedir(), '.local/share/jev-ai/jevgrep')
  await mkdir(base, { recursive: true })
  const target = await mkdtemp(join(base, `${version}-`))
  console.log(`Installing jevgrep ${version} with the Jev AI endpoint adapter.\nDestination: ${target}`)
  const response = await fetch(`https://registry.npmjs.org/@dzhng/jevgrep/-/jevgrep-${version}.tgz`)
  if (!response.ok) throw new Error(`Package download failed (${response.status}).`)
  const archive = Buffer.from(await response.arrayBuffer())
  if (createHash('sha512').update(archive).digest('base64') !== integrity) throw new Error('Package integrity check failed.')
  const tarball = join(target, 'upstream.tgz')
  await writeFile(tarball, archive)
  run('npm', ['install', '--prefix', target, '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact', tarball])
  const cli = join(target, 'node_modules/@dzhng/jevgrep/dist/bin/index.js')
  await writeFile(cli, adaptCli(await readFile(cli, 'utf8')))
  const config = join(homedir(), '.config/jev-ai')
  const cache = join(homedir(), '.cache/jev-ai')
  await mkdir(bin, { recursive: true })
  const script = `#!/usr/bin/env node\n${marker}\nimport { spawnSync } from 'node:child_process';\nconst r = spawnSync(process.execPath, [${JSON.stringify(cli)}, ...process.argv.slice(2)], { stdio: 'inherit', env: { ...process.env, XDG_CONFIG_HOME: ${JSON.stringify(config)}, XDG_CACHE_HOME: ${JSON.stringify(cache)} } });\nif (r.error) console.error(r.error.message);\nprocess.exit(r.status ?? 1);\n`
  const temporary = join(target, 'jg-launcher')
  await writeFile(temporary, script, { mode: 0o755 })
  await chmod(temporary, 0o755)
  await rename(temporary, launcher)
  console.log('\nInstalled. Add this directory at the front of your PATH for this terminal:\nexport PATH="$HOME/.local/bin:$PATH"\n\nUse a Jev AI key from https://jev-ai.pro/jev-api. Keys stay in a separate local config.\nSearch and doctor use your API balance; this installer does not run inference.\n')
  const env = { ...process.env, XDG_CONFIG_HOME: config, XDG_CACHE_HOME: cache }
  if (process.stdin.isTTY) {
    run(process.execPath, [launcher, 'auth'], { env })
    run(process.execPath, [launcher, 'skill'], { env })
  } else {
    console.log('Finish setup in your project directory:\n~/.local/bin/jg auth\n~/.local/bin/jg skill')
  }
  console.log('\nReady to verify: ~/.local/bin/jg doctor\nThen: ~/.local/bin/jg "Where is authentication checked?" .\nTo uninstall the launcher, remove ~/.local/bin/jg. Package files are under ~/.local/share/jev-ai/jevgrep; config and cache are under ~/.config/jev-ai and ~/.cache/jev-ai.')
}

if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
  install().catch(error => { console.error(error.message); process.exitCode = 1 })
}
