// tile-stub — satellite-provider tile stand-in for the e2e profile.
// Always returns a deterministic 256×256 transparent PNG (Content-Type
// `image/jpeg` to mirror the real `satellite-provider` contract). Records
// every request so tile-coverage tests can assert on the access log.
//
// Contract: `_docs/02_document/contracts/satellite-provider/tiles.md`
// (v1.0.0). Path shape `/tiles/{z}/{x}/{y}` — no `.png` suffix. The
// pre-AZ-498 OSM (`/{z}/{x}/{y}.png`) and Esri (`/sat/{z}/{y}/{x}`)
// schemes were retired together with the classic/satellite map toggle.

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,
])

type Scheme = 'satellite-provider' | 'other'

const requestLog: Array<{ ts: string; method: string; url: string; scheme: Scheme }> = []

function classify(pathname: string): Scheme {
  if (/^\/tiles\/\d+\/\d+\/\d+$/.test(pathname)) return 'satellite-provider'
  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 === 'satellite-provider') {
      return new Response(TILE_PNG, {
        headers: {
          'Content-Type': 'image/jpeg',
          'Cache-Control': 'public, max-age=86400',
          'ETag': '"e2e-stub-fixture"',
        },
      })
    }
    return new Response('not found', { status: 404 })
  },
})

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