// `__DEV__`-only deep-link seam that logs a session in from a rig file,
// replacing the OAuth UI as the entry point for the Maestro E2E tier.
//
// A flow fires `openLink: halflight://__dev_seed`. This listener reads the rig
// JSON that `scripts/dev/run-e2e.sh` placed at `Documents/devnet/e2e-rig.json`,
// seeds every account, activates the first, deletes the file (so credentials
// don't linger on the sim disk), and lands on the home feed.
//
// Why a file, not a URL payload: iOS truncates `openURL` URLs at ~2 KB, and a
// single Pixelfed JWT access+refresh pair already blows past that. The deep
// link stays the *trigger*; the file is just the payload channel. The read is
// only ever reached through this `__DEV__`-gated handler — never at boot — so a
// release build (which renders null below) cannot load credentials from disk.

import { Directory, File, Paths } from 'expo-file-system'
import * as Linking from 'expo-linking'
import { useRouter } from 'expo-router'
import { useEffect, useRef } from 'react'
import { seedFromRigJson } from 'src/lib/devSeed'

const SEED_HOST = '__dev_seed'
const RIG_FILE = 'e2e-rig.json'

function DevSeedListenerInner() {
  const url = Linking.useURL()
  const router = useRouter()
  const handled = useRef<string | null>(null)

  useEffect(() => {
    if (!url || handled.current === url) return
    const parsed = Linking.parse(url)
    // expo-linking puts the authority of `scheme://authority` in `hostname`;
    // some shapes land it in `path`. Match either.
    if (parsed.hostname !== SEED_HOST && parsed.path !== SEED_HOST) return
    handled.current = url

    try {
      const file = new File(new Directory(Paths.document, 'devnet'), RIG_FILE)
      if (!file.exists) {
        // eslint-disable-next-line no-console
        console.warn(
          `[dev-seed] no rig file at devnet/${RIG_FILE} — run scripts/dev/run-e2e.sh`
        )
        return
      }
      const json = file.textSync()
      const { count, activeAccountId } = seedFromRigJson(json)
      // Don't leave bearer tokens sitting on the sim disk after seeding.
      file.delete()
      // eslint-disable-next-line no-console
      console.log(
        `[dev-seed] seeded ${count} account(s); active=${activeAccountId.slice(0, 8)}…`
      )
      // Explicit landing so the flow's `home-feed` assertion settles fast;
      // AuthProvider's useProtectedRoute is the backstop if this races.
      router.replace('/(auth)/(tabs)/home')
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error('[dev-seed] seeding failed:', (e as Error).message)
    }
  }, [url, router])

  return null
}

export function DevSeedListener() {
  if (!__DEV__) return null
  return <DevSeedListenerInner />
}
