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'

async function removeIfExists(path: string): Promise<void> {
  try {
    await Deno.remove(path, { recursive: true })
    console.log(`Removed: ${path}`)
  } catch {
    // already gone
  }
}

export const cleanCmd = new Command()
  .name('clean')
  .description('Remove intermediate .osm.pbf and .poly files.')
  .option(
    '--region <region:string>',
    'Remove files for a specific region only.',
  )
  .option('--all', 'Remove all intermediate files.')
  .action(async ({ region, all }) => {
    if (all) {
      await removeIfExists(PBF_DIR)
      await removeIfExists(POLY_DIR)
    } else if (region) {
      const parts = region.split('/')
      const pbfPath = join(
        PBF_DIR,
        ...parts.slice(0, -1),
        `${leafName(region)}-latest.osm.pbf`,
      )
      const polyPath = join(
        POLY_DIR,
        ...parts.slice(0, -1),
        `${leafName(region)}.poly`,
      )
      await removeIfExists(pbfPath)
      await removeIfExists(polyPath)
    } else {
      console.error('Provide --region <slug> or --all.')
      Deno.exit(1)
    }
  })
