import { Command } from '@cliffy/command'
import { ensureDir } from '@std/fs'
import { join } from '@std/path'
import { PBF_DIR } from '../shared/paths.ts'

const BASE_URL = 'https://download.geofabrik.de'

export const downloadOsmCmd = new Command()
  .name('download:osm')
  .description(
    'Download a regional .osm.pbf file from Geofabrik. e.g. "europe/spain"',
  )
  .arguments('<region:string>')
  .option('--force', 'Re-download even if the file already exists.')
  .action(async ({ force }, region) => {
    const parts = region.split('/')
    const filename = `${parts[parts.length - 1]}-latest.osm.pbf`
    const outDir = join(PBF_DIR, ...parts.slice(0, -1))
    const outPath = join(outDir, filename)

    await ensureDir(outDir)

    if (!force && (await Deno.stat(outPath).catch(() => null))) {
      console.log(`Already exists: ${outPath}`)
      console.log('Use --force to re-download.')
      return
    }

    const url = `${BASE_URL}/${region}-latest.osm.pbf`
    console.log(`Downloading ${url} ...`)

    const response = await fetch(url)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const file = await Deno.open(outPath, {
      write: true,
      create: true,
      truncate: true,
    })
    await response.body!.pipeTo(file.writable)

    console.log(`Saved: ${outPath}`)
  })
