import { Command } from '@cliffy/command'
import { join } from '@std/path'
import { PBF_DIR, POLY_DIR } from '../shared/paths.ts'
import { leafName } from '../shared/regions.ts'
import { run } from '../shared/run.ts'

export const extractCmd = new Command()
  .name('extract')
  .description('Extract a sub-region from a larger .osm.pbf using osmium.')
  .arguments('<region:string>')
  .option('--from <source:string>', 'Source region slug to extract from.', {
    required: true,
  })
  .action(async ({ from: source }, region) => {
    const sourceParts = source.split('/')
    const sourcePbf = join(
      PBF_DIR,
      ...sourceParts.slice(0, -1),
      `${leafName(source)}-latest.osm.pbf`,
    )

    const regionParts = region.split('/')
    const polyFile = join(
      POLY_DIR,
      ...regionParts.slice(0, -1),
      `${leafName(region)}.poly`,
    )
    const outPbf = join(
      PBF_DIR,
      ...regionParts.slice(0, -1),
      `${leafName(region)}-latest.osm.pbf`,
    )

    if (!(await Deno.stat(sourcePbf).catch(() => null))) {
      throw new Error(
        `Source PBF not found: ${sourcePbf}\nRun: deno task data download:osm ${source}`,
      )
    }
    if (!(await Deno.stat(polyFile).catch(() => null))) {
      throw new Error(
        `Poly file not found: ${polyFile}\nRun: deno task data download:poly ${region}`,
      )
    }

    console.log(`Extracting ${region} from ${source} ...`)

    await run('osmium', [
      'extract',
      '--progress',
      '--polygon',
      polyFile,
      '--strategy',
      'complete_ways',
      '--overwrite',
      sourcePbf,
      '--output',
      outPbf,
    ])

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