#!/usr/bin/env node
import { readFileSync } from 'node:fs'
import { WaHttpRegistrationFlow } from '../src/auth/registration/WaHttpRegistrationFlow'
import { parseAndroidApkMaterial } from '../src/auth/registration/token'
import { ConsoleLogger } from '../src/infra/log/ConsoleLogger'
import type { LogLevel } from '../src/infra/log/types'
import { WaAuthMemoryStore } from '../src/store/memory/auth.store'
import { WaPreKeyMemoryStore } from '../src/store/memory/pre-key.store'
import { WaSignalMemoryStore } from '../src/store/memory/signal.store'

function resolveLogLevel(value: string | undefined): LogLevel {
    switch (value) {
        case 'trace':
        case 'debug':
        case 'info':
        case 'warn':
        case 'error':
            return value
        default:
            return 'info'
    }
}

async function main() {
    const logger = new ConsoleLogger(resolveLogLevel(process.env.LOG_LEVEL))
    const authStore = new WaAuthMemoryStore()
    const signalStore = new WaSignalMemoryStore()
    const preKeyStore = new WaPreKeyMemoryStore()

    // Android has no static token: its token is an HMAC over the APK signing
    // certificates, classes.dex and about_logo.png. Point this at the JSON
    // produced by `wa apk-material` (whalibmob) or register as iOS instead.
    const materialPath = process.env.WA_ANDROID_APK_MATERIAL
    const androidApkMaterial = materialPath
        ? parseAndroidApkMaterial(JSON.parse(readFileSync(materialPath, 'utf8')))
        : undefined

    const flow = new WaHttpRegistrationFlow({
        logger,
        authStore,
        signalStore,
        preKeyStore,
        androidApkMaterial,
        // Override the registration endpoint (defaults to https://v.whatsapp.net).
        // Useful to point the flow at a local mock server.
        baseUrl: process.env.WA_REGISTRATION_BASE_URL || undefined
    })

    // 1) Load/create fresh credentials
    await flow.loadOrCreateKeys()
    console.log('Keys loaded/created')

    // 2) Request code
    const cc = process.env.CC || ''
    const inNum = process.env.NUMBER || ''
    if (!cc || !inNum) {
        console.error('Set CC and NUMBER env vars')
        process.exit(1)
    }

    // Registering as iOS needs no APK material: the iOS token is derived from
    // the static prefix and the app version. `WA_REGISTRATION_OS=ios` switches
    // the whole flow (UA, token formula, device profile) to iOS.
    const registrationOs = process.env.WA_REGISTRATION_OS === 'ios' ? 'ios' : 'android'
    if (registrationOs === 'android' && !androidApkMaterial) {
        console.error(
            'Android registration needs APK material. Set WA_ANDROID_APK_MATERIAL to the ' +
                'JSON from `wa apk-material`, or set WA_REGISTRATION_OS=ios.'
        )
        process.exit(1)
    }
    const deviceInfo = registrationOs === 'ios' ? { os: 'ios' as const } : undefined

    const method = (process.env.METHOD as 'sms' | 'voice') || 'sms'
    const codeResult = await flow.requestCode({ cc, in: inNum, method, deviceInfo })
    console.log('Code result:', codeResult)

    if (codeResult.status !== 'sent') {
        process.exit(1)
    }

    // 3) Wait for code (interactive)
    const readline = await import('node:readline')
    const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
    const code = await new Promise<string>((resolve) => {
        rl.question('Enter SMS code: ', (ans) => {
            rl.close()
            resolve(ans.trim())
        })
    })

    // 4) Register
    const reg = await flow.registerPhone({ cc, in: inNum, method, code, deviceInfo })
    console.log('Registered:', reg.meJid)

    // 5) Now can connect as mobile primary with WaClient
    console.log('Credentials stored in authStore with meJid set')
}

main().catch((e) => {
    console.error(e)
    process.exit(1)
})
