// tile-stub — OSM + Esri tile stand-in for the e2e profile (AZ-456 AC-2).
// Always returns a deterministic 256×256 transparent PNG. Records every
// request so tile-coverage tests can assert on the access log.

const PORT = Number(process.env.PORT ?? 8082)

const TILE_PNG = new Uint8Array([
  0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
  0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x06, 0x00, 0x00, 0x00, 0x5c, 0x72, 0xa8,
  0x66, 0x00, 0x00, 0x00, 0x10, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0xed, 0xc1, 0x01, 0x0d, 0x00,
  0x00, 0x00, 0xc2, 0xa0, 0xf7, 0x4f, 0x6d, 0x0e, 0x37, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
  0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
])

const requestLog: Array<{ ts: string; method: string; url: string; scheme: 'osm' | 'esri' | 'other' }> = []

function classify(pathname: string): 'osm' | 'esri' | 'other' {
  if (/^\/sat\//.test(pathname)) return 'esri'
  if (/^\/\d+\/\d+\/\d+\.png$/.test(pathname)) return 'osm'
  return 'other'
}

const server = Bun.serve({
  port: PORT,
  fetch(req) {
    const url = new URL(req.url)
    const scheme = classify(url.pathname)
    requestLog.push({ ts: new Date().toISOString(), method: req.method, url: url.pathname, scheme })

    if (url.pathname === '/health') {
      return new Response('ok', { status: 200 })
    }
    if (url.pathname === '/mock/log') {
      return Response.json(requestLog)
    }
    if (scheme === 'osm' || scheme === 'esri') {
      return new Response(TILE_PNG, { headers: { 'Content-Type': 'image/png' } })
    }
    return new Response('not found', { status: 404 })
  },
})

console.log(`[tile-stub] listening on :${server.port}`)
