/**
 * Publish out/release/<version>/ as the GitLab release for tag v<version>:
 *
 *   bun tools/release.ts [--push] [--notes notes.md]
 *
 * The token (api scope) comes from GITLAB_TOKEN, else from the file at GITLAB_TOKEN_FILE
 * (default ~/.config/factoriomodmanager-release/gitlab-token, mode 600).
 * The project and host come from the `origin` remote. Files go to the project's generic package
 * registry and become release links with permanent /-/releases/<tag>/downloads/<file> URLs.
 * The tag must already be on origin; --push first pushes the current branch and the tag
 * (creating an annotated tag at HEAD when missing). Rerunning adds only missing files.
 * Pass --notes RELEASE_NOTES.md to set or revise the description. Otherwise new releases
 * get installation instructions for the uploaded packages.
 */
import { spawnSync } from 'node:child_process'
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import { homedir } from 'node:os'
import path from 'node:path'

import { workspaceVersion } from './package'

const root = path.resolve(import.meta.dir, '..')
const PACKAGE = 'factoriomodmanager'

/** git@host:group/project.git, ssh://git@host[:port]/group/project.git or https://host/group/project(.git) */
export function parseRemote(url: string): { host: string, project: string } {
  const m = /^(?:ssh:\/\/)?[^@/]+@([^:/]+)(?::\d+)?[:/](.+?)(?:\.git)?\/?$/.exec(url)
    ?? /^https?:\/\/(?:[^@/]+@)?([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(url)
  if (!m?.[1] || !m[2]) throw new Error(`Unrecognised remote URL: ${url}`)
  // Our SSH config maps the web host to ssh.<host> for Git; the API lives on the web host.
  return { host: m[1].replace(/^ssh\./, ''), project: m[2] }
}

export function releaseNotes(version: string, files: string[]): string {
  const has = (suffix: string) => files.some(f => f.endsWith(suffix))
  const lines = [`Factorio Mod Manager ${version}.`, '', '## Install', '']
  if (has('-macos-universal.dmg')) lines.push('- **macOS:** Drag the app to Applications. If macOS blocks the first launch, check Privacy & Security.')
  if (has('-windows-x86_64.exe')) lines.push('- **Windows 10/11:** Download and run the portable x86-64 executable.')
  if (has('-linux-x86_64.AppImage')) lines.push('- **Linux:** Use the x86-64 AppImage on a system with glibc 2.35+.')
  if (has('-arch-x86_64.pkg.tar.zst')) lines.push('- **Arch Linux:** Install the download with `sudo pacman -U <package>`.')
  return lines.join('\n') + '\n'
}

function git(args: string[]): string {
  const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['inherit', 'pipe', 'inherit'] })
  if (r.status !== 0) throw new Error(`git ${args.join(' ')} failed`)
  return r.stdout.trim()
}

async function api(base: string, token: string, method: string, route: string, body?: string | Blob, json = true) {
  const res = await fetch(`${base}/api/v4${route}`, {
    method,
    headers: { 'PRIVATE-TOKEN': token, ...(json && body ? { 'Content-Type': 'application/json' } : {}) },
    body,
  })
  const text = await res.text()
  if (!res.ok && res.status !== 404) throw new Error(`${method} ${route}: ${res.status} ${text.slice(0, 300)}`)
  return { status: res.status, data: text ? JSON.parse(text) : null }
}

async function main() {
  const args = process.argv.slice(2)
  const push = args.includes('--push')
  const notesIndex = args.indexOf('--notes')
  const notes = notesIndex >= 0 ? readFileSync(args[notesIndex + 1] ?? '', 'utf8') : undefined
  const tokenFile = process.env.GITLAB_TOKEN_FILE ?? path.join(homedir(), '.config/factoriomodmanager-release/gitlab-token')
  const token = process.env.GITLAB_TOKEN ?? (existsSync(tokenFile) ? readFileSync(tokenFile, 'utf8').trim() : '')
  if (!token) throw new Error(`Set GITLAB_TOKEN or save an api-scope token in ${tokenFile}`)

  const version = workspaceVersion(readFileSync(path.join(root, 'Cargo.toml'), 'utf8'))
  const tag = `v${version}`
  const dir = path.join(root, 'out/release', version)
  const files = existsSync(dir) ? readdirSync(dir).filter(f => f.startsWith(`FactorioModManager-${version}-`)).sort() : []
  if (files.length === 0) throw new Error(`Nothing to publish in ${path.relative(root, dir)}; run bun tools/package.ts all`)

  const { host, project } = parseRemote(git(['remote', 'get-url', 'origin']))
  const base = `https://${host}`
  const id = encodeURIComponent(project)

  if (push) {
    if (git(['-c', 'core.fileMode=false', 'status', '--porcelain', '--untracked-files=no'])) {
      throw new Error('Uncommitted changes; the tag would not match the packages')
    }
    if (!spawnSync('git', ['rev-parse', '-q', '--verify', `refs/tags/${tag}`], { cwd: root }).stdout.length) {
      git(['tag', '-a', tag, '-m', `Factorio Mod Manager ${version}`])
    }
    git(['push', 'origin', 'HEAD', tag])
  }
  if (!git(['ls-remote', '--tags', 'origin', `refs/tags/${tag}`])) {
    throw new Error(`${tag} is not on origin; rerun with --push`)
  }

  const links = []
  for (const name of files) {
    const route = `/projects/${id}/packages/generic/${PACKAGE}/${version}/${encodeURIComponent(name)}`
    const size = statSync(path.join(dir, name)).size
    console.log(`[release] upload ${name} (${(size / 1048576).toFixed(1)} MiB)`)
    await api(base, token, 'PUT', route, Bun.file(path.join(dir, name)), false)
    links.push({ name, url: `${base}/api/v4${route}`, direct_asset_path: `/${name}`, link_type: name.endsWith('.pkg.tar.zst') ? 'package' : 'other' })
  }

  const release = await api(base, token, 'GET', `/projects/${id}/releases/${tag}`)
  if (release.status === 404) {
    const description = notes ?? releaseNotes(version, files)
    await api(base, token, 'POST', `/projects/${id}/releases`, JSON.stringify({
      name: `Factorio Mod Manager ${version}`, tag_name: tag, description, assets: { links },
    }))
  } else {
    if (notes !== undefined) {
      await api(base, token, 'PUT', `/projects/${id}/releases/${tag}`, JSON.stringify({ description: notes }))
    }
    const existing = new Set((release.data.assets?.links ?? []).map((l: { name: string }) => l.name))
    for (const link of links.filter(l => !existing.has(l.name))) {
      await api(base, token, 'POST', `/projects/${id}/releases/${tag}/assets/links`, JSON.stringify(link))
    }
  }
  console.log(`[release] ${base}/${project}/-/releases/${tag}`)
}

if (import.meta.main) await main()
