import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs'
import { createSqliteStore } from '../packages/store-sqlite/src/createSqliteStore'
import { ConsoleLogger } from '../src/infra/log/ConsoleLogger'
import { createStore, WaClient } from '../src'

const MATRIX = process.env.MATRIX_URL || 'http://127.0.0.1:8449'
const TOKEN = process.env.MATRIX_TOKEN || ''
const BOT = process.env.MATRIX_BOT || '@whatsapp:matrix2.marlonivo.com'
const ROOM = process.env.MATRIX_ROOM || ''
const DOMAIN = process.env.MATRIX_DOMAIN || 'marlonivo.com'
const REG = process.env.MATRIX_REG || '/etc/mautrix/whatsapp/registration.yaml'
const WA_DB = process.env.AUTH_DB || '/mnt/marlonivo.com/home/ivo/ongoing/code/zapo/regstate/primary-fresh2.sqlite'
const MIRROR = process.env.MIRROR_ROOM || ''
const SELF = (process.env.SELF_JID || '').split(',').filter(Boolean)
const STATE_DIR = '/var/lib/wa-bridge'
const STATE = STATE_DIR + '/state.json'
const MEDIA_DIR = STATE_DIR + '/media'
const MEDIA_KIND: Record<string, 'image' | 'video' | 'audio' | 'document'> = {
    'm.image': 'image',
    'm.video': 'video',
    'm.audio': 'audio',
    'm.file': 'document'
}

mkdirSync(STATE_DIR, { recursive: true })
mkdirSync(MEDIA_DIR, { recursive: true })

let state: { since?: string; target?: string; rooms?: Record<string, string> } = {}
try {
    state = JSON.parse(readFileSync(STATE, 'utf8'))
} catch {
    state = {}
}
try {
    const seed = JSON.parse(readFileSync(STATE_DIR + '/rooms.json', 'utf8')) as Record<string, string>
    state.rooms = { ...seed, ...(state.rooms ?? {}) }
} catch {
    state.rooms = state.rooms ?? {}
}

function save(): void {
    writeFileSync(STATE, JSON.stringify(state))
}

const HEARTBEAT = STATE_DIR + '/heartbeat.json'
let waState = 'init'
let syncRooms = 0
let waConnected = false
let reconnecting = false
let reconnectDelay = 5000
let okTs = Math.floor(Date.now() / 1000)

function beat(sync: number): void {
    try {
        const now = Math.floor(Date.now() / 1000)
        const ok = sync === 200 && waConnected
        if (ok) okTs = now
        writeFileSync(HEARTBEAT, JSON.stringify({
            ts: now,
            pid: process.pid,
            wa: waState,
            sync,
            rooms: syncRooms,
            ok,
            ok_ts: okTs
        }))
    } catch {
    }
}

function registration(): { token: string; sender: string } {
    try {
        const raw = readFileSync(REG, 'utf8')
        const token = /^as_token:\s*(\S+)/m.exec(raw)?.[1] ?? ''
        const sender = /^sender_localpart:\s*(\S+)/m.exec(raw)?.[1] ?? ''
        return { token, sender: sender ? '@' + sender + ':' + DOMAIN : BOT }
    } catch {
        return { token: '', sender: BOT }
    }
}

const reg = registration()

async function mcall(
    method: string,
    path: string,
    body?: unknown,
    token: string = TOKEN,
    asUser?: string
): Promise<number> {
    const url = MATRIX + path + (asUser ? '?user_id=' + encodeURIComponent(asUser) : '')
    const res = await fetch(url, {
        method,
        headers: {
            'Content-Type': 'application/json',
            Authorization: 'Bearer ' + token
        },
        body: body === undefined ? undefined : JSON.stringify(body)
    })
    return res.status
}

async function matrixMedia(
    content: { url?: string; info?: { mimetype?: string; size?: number } },
    kind: 'image' | 'video' | 'audio' | 'document'
): Promise<{ path: string; kind: typeof kind; mimetype: string } | null> {
    const url = content?.url
    if (!url?.startsWith('mxc://')) return null
    const rest = url.slice(6)
    const slash = rest.indexOf('/')
    if (slash < 1) return null
    const server = rest.slice(0, slash)
    const id = rest.slice(slash + 1)
    if (!/^[A-Za-z0-9_-]+$/.test(id)) return null
    if ((content.info?.size ?? 0) > 100 * 1024 * 1024) return null

    const download = MATRIX + '/_matrix/media/v3/download/' +
        encodeURIComponent(server) + '/' + encodeURIComponent(id)
    const res = await fetch(download, {
        headers: TOKEN ? { Authorization: 'Bearer ' + TOKEN } : {}
    })
    if (!res.ok) return null

    const bytes = Buffer.from(await res.arrayBuffer())
    if (!bytes.length || bytes.length > 100 * 1024 * 1024) return null

    const ext = { image: '.jpg', video: '.mp4', audio: '.ogg', document: '.bin' }[kind]
    const path = MEDIA_DIR + '/' + id + ext
    writeFileSync(path, bytes)
    return {
        path,
        kind,
        mimetype: content.info?.mimetype || 'application/octet-stream'
    }
}

function ghostMxid(jid?: string): string | undefined {
    if (!jid) return undefined
    const at = jid.indexOf('@')
    if (at < 0) return undefined
    const user = jid.slice(0, at)
    const server = jid.slice(at + 1)
    if (server === 'lid') return '@whatsapp_lid-' + user + ':' + DOMAIN
    if (server === 's.whatsapp.net') return '@whatsapp_' + user + ':' + DOMAIN
    return undefined
}

async function sendToMatrix(room: string, body: string, senderJid?: string, relayBody?: string): Promise<void> {
    if (!room) return
    const txn = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
    const path = '/_matrix/client/v3/rooms/' + encodeURIComponent(room) +
        '/send/m.room.message/' + txn
    const text = relayBody ?? body
    const ghost = reg.token ? ghostMxid(senderJid) : undefined
    if (ghost) {
        const code = await mcall('PUT', path, { msgtype: 'm.text', body }, reg.token, ghost)
        if (code === 200) return
    }
    if (reg.token) {
        const relay = '@whatsappbot:' + DOMAIN
        const code = await mcall('PUT', path, { msgtype: 'm.text', body: text }, reg.token, relay)
        if (code === 200) return
    }
    await mcall('PUT', path, { msgtype: 'm.text', body: text })
}

function extractText(message: unknown): string | undefined {
    const m = message as
        | { conversation?: string | null; extendedTextMessage?: { text?: string | null } | null }
        | null
        | undefined
    if (m?.conversation) return m.conversation
    if (m?.extendedTextMessage?.text) return m.extendedTextMessage.text
    return undefined
}

type MediaContent = { type: 'image' | 'video' | 'audio' | 'document'; mimetype: string; caption?: string }

function extractMediaContent(message: unknown): MediaContent | undefined {
    const m = message as Record<string, unknown> | null | undefined
    if (!m) return undefined
    const types: [string, MediaContent['type']][] = [
        ['imageMessage', 'image'],
        ['videoMessage', 'video'],
        ['audioMessage', 'audio'],
        ['documentMessage', 'document'],
        ['stickerMessage', 'image']
    ]
    for (const [key, type] of types) {
        const raw = m[key] as { mimetype?: string; caption?: string } | null | undefined
        if (raw) {
            const mimetype = raw.mimetype || (type === 'image' ? 'image/jpeg' : 'application/octet-stream')
            return { type, mimetype, caption: raw.caption }
        }
    }
    return undefined
}

async function matrixUpload(bytes: Uint8Array, mimetype: string): Promise<string | undefined> {
    try {
        const res = await fetch(MATRIX + '/_matrix/media/v3/upload', {
            method: 'POST',
            headers: { 'Content-Type': mimetype, Authorization: 'Bearer ' + TOKEN },
            body: Buffer.from(bytes)
        })
        if (!res.ok) {
            console.log('[wa->mx] media upload failed', res.status)
            return undefined
        }
        const json = await res.json() as { content_uri?: string }
        return json.content_uri
    } catch (err) {
        console.log('[wa->mx] media upload error', String(err))
        return undefined
    }
}

async function sendToMatrixMedia(
    room: string,
    mxc: string,
    body: string,
    msgtype: string,
    info: { mimetype: string; size: number },
    senderJid?: string,
    relayBody?: string
): Promise<void> {
    if (!room) return
    const txn = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
    const path = '/_matrix/client/v3/rooms/' + encodeURIComponent(room) +
        '/send/m.room.message/' + txn
    const content = { msgtype, body: relayBody ?? body, url: mxc, info }
    const ghost = reg.token ? ghostMxid(senderJid) : undefined
    if (ghost) {
        if (await mcall('PUT', path, content, reg.token, ghost) === 200) return
    }
    if (reg.token) {
        if (await mcall('PUT', path, content, reg.token, '@whatsappbot:' + DOMAIN) === 200) return
    }
    await mcall('PUT', path, content)
}

function roomFor(jid: string, key: { remoteJidAlt?: string; participant?: string; participantAlt?: string }): string {
    const rooms = state.rooms ?? {}
    for (const candidate of [jid, key.remoteJidAlt, key.participant, key.participantAlt]) {
        if (candidate && rooms[candidate]) return rooms[candidate]
    }
    return ROOM
}

const logger = new ConsoleLogger('info')
const sqlite = createSqliteStore({ path: WA_DB, logger })
const store = createStore({
    backends: { sqlite },
    providers: {
        auth: 'sqlite', signal: 'sqlite', preKey: 'sqlite', session: 'sqlite',
        identity: 'sqlite', senderKey: 'sqlite', appState: 'sqlite',
        privacyToken: 'sqlite', messages: 'sqlite', threads: 'sqlite', contacts: 'sqlite'
    }
})
const client = new WaClient({ store, sessionId: 'default', connectTimeoutMs: 30000 }, logger)

client.on('connection', (e) => {
    waState = e.status + (e.reason ? ':' + e.reason : '')
    waConnected = e.status === 'open'
    beat(0)
    console.log('[wa]', e.status, e.reason ?? '')
    if (e.status === 'open') {
        reconnectDelay = 5000
        return
    }
    if (e.isLogout) {
        console.log('[wa] logged out, no reconnect')
        return
    }
    scheduleReconnect()
})

function scheduleReconnect(): void {
    if (reconnecting) return
    reconnecting = true
    const delay = reconnectDelay
    reconnectDelay = Math.min(reconnectDelay * 2, 60000)
    console.log('[wa] reconnect in ' + delay + 'ms')
    setTimeout(() => {
        void reconnect()
    }, delay)
}

async function reconnect(): Promise<void> {
    try {
        console.log('[wa] reconnecting')
        try {
            await client.disconnect()
        } catch {
        }
        await client.connect()
        console.log('[wa] reconnect done')
    } catch (err) {
        console.log('[wa] reconnect failed', String(err))
        scheduleReconnect()
    } finally {
        reconnecting = false
    }
}

async function relayIncomingMedia(
    room: string,
    jid: string,
    bytes: Uint8Array,
    media: { type: 'image' | 'video' | 'audio' | 'document'; mimetype: string; caption?: string },
    senderJid?: string,
    name?: string
): Promise<void> {
    const mxc = await matrixUpload(bytes, media.mimetype)
    if (!mxc) throw new Error('upload failed')
    const msgtype = 'm.' + media.type
    const caption = media.caption || media.type
    const body = (name ?? '') + caption
    const info = { mimetype: media.mimetype, size: bytes.length }
    await sendToMatrixMedia(room, mxc, body, msgtype, info, senderJid, body)
    if (MIRROR && MIRROR !== room) {
        await sendToMatrixMedia(MIRROR, mxc, body, msgtype, info, senderJid, body)
    }
    console.log('[wa->mx] media', jid, room, media.type, bytes.length, mxc)
}

client.on('message', async (event) => {
    const jid = event.key.remoteJid
    if (!jid) return
    const self = SELF.includes(jid)
    if (event.key.fromMe && !self) return
    if (!event.key.fromMe) console.log('[dbg] msg keys', jid, JSON.stringify(Object.keys(event.message ?? {})))
    const text = extractText(event.message)
    const media = text ? undefined : extractMediaContent(event.message)
    if (!text && !media) return
    state.target = jid
    save()
    const senderJid = event.key.participant ?? jid
    const name = event.pushName ? event.pushName + ': ' : ''
    const room = roomFor(jid, event.key)
    if (media) {
        try {
            const bytes = await client.message.downloadBytes(event, { maxBytes: 100 * 1024 * 1024 })
            await relayIncomingMedia(room, jid, bytes, media, senderJid, name)
        } catch (err) {
            console.log('[wa->mx] media failed', jid, String(err))
        }
        return
    }
    if (event.key.fromMe) console.log('[wa-fromme]', jid, text!.slice(0, 40))
    await sendToMatrix(room, text!, senderJid, name + text)
    if (MIRROR && MIRROR !== room) {
        await sendToMatrix(MIRROR, text!, senderJid, name + text)
    }
    console.log('[wa->mx]', jid, room)
})

const SELFTEST = STATE_DIR + '/selftest.json'

async function drainSelfTest(): Promise<void> {
    let job: { path?: string; mimetype?: string; caption?: string; room?: string } | null = null
    try {
        job = JSON.parse(readFileSync(SELFTEST, 'utf8'))
    } catch {
        return
    }
    rmSync(SELFTEST, { force: true })
    if (!job?.path || !existsSync(job.path)) {
        console.log('[selftest] missing path', job?.path)
        return
    }
    try {
        const bytes = new Uint8Array(readFileSync(job.path))
        const mimetype = job.mimetype || 'image/png'
        const room = job.room || state.target || ROOM
        const fakeImageMessage = { imageMessage: { mimetype, caption: job.caption || 'zappa selftest' } }
        const detected = extractMediaContent(fakeImageMessage)
        if (!detected) throw new Error('extractMediaContent failed on imageMessage')
        console.log('[selftest] extractMediaContent OK', JSON.stringify(detected))
        await relayIncomingMedia(room, 'selftest', bytes, detected)
        console.log('[selftest] wa->mx media OK (real extract+relay)', room, bytes.length)
    } catch (err) {
        console.log('[selftest] FAILED', String(err))
    }
}

const NON_HUMAN = /^@(whatsapp|telegram|signal|line|kakao|irc|mail|meta|gmessages)/
const OUTBOX = STATE_DIR + '/outbox.json'
const STATUS = STATE_DIR + '/status-outbox.json'

type OutboxItem = { jid: string; body: string; path?: string; kind?: string; mimetype?: string }
const FAILED_MEDIA = new Set<string>()

function queueOutbox(jid: string, body: string, media?: { path: string; kind?: string; mimetype: string }): void {
    let list: OutboxItem[] = []
    try {
        list = JSON.parse(readFileSync(OUTBOX, 'utf8'))
    } catch {
    }
    const item: OutboxItem = { jid, body }
    if (media) {
        item.path = media.path
        item.kind = media.kind
        item.mimetype = media.mimetype
        FAILED_MEDIA.add(media.path)
    }
    list.push(item)
    try {
        writeFileSync(OUTBOX, JSON.stringify(list.slice(-500)))
    } catch (err) {
        console.log('[outbox] queue failed', String(err))
    }
}

const STATUS_RESULT = STATE_DIR + '/status-result.json'

async function drainOutbox(): Promise<void> {
    let list: OutboxItem[] = []
    try {
        list = JSON.parse(readFileSync(OUTBOX, 'utf8'))
    } catch {
        return
    }
    const pending: OutboxItem[] = []
    for (const item of list) {
        if (!item.jid || (!item.body && !item.path)) continue
        try {
            if (!waConnected) throw new Error('client is not connected')
            const sent = item.path && existsSync(item.path)
                ? await client.message.send(item.jid, {
                    type: item.kind || 'image',
                    media: item.path,
                    mimetype: item.mimetype || 'application/octet-stream',
                    caption: item.body || ''
                } as never)
                : await client.message.send(item.jid, item.body)
            console.log('[outbox]', item.jid, sent.id)
            if (item.path) {
                rmSync(item.path, { force: true })
                FAILED_MEDIA.delete(item.path)
            }
            if (SELF.includes(item.jid)) {
                const target = state.rooms?.[item.jid] || ROOM
                if (target) {
                    const local = item.jid.split('@')[0]
                    const sender = item.jid.endsWith('@lid')
                        ? '@whatsapp_lid-' + local + ':' + DOMAIN
                        : '@whatsapp_' + local + ':' + DOMAIN
                    const txn = Date.now().toString(36) + Math.random().toString(36).slice(2, 8)
                    await mcall('PUT', '/_matrix/client/v3/rooms/' + encodeURIComponent(target) +
                        '/send/m.room.message/' + txn, { msgtype: 'm.text', body: item.body },
                        reg.token, sender)
                }
            }
        } catch (err) {
            console.log('[outbox] failed', String(err))
            pending.push(item)
        }
    }
    if (pending.length > 0) {
        writeFileSync(OUTBOX, JSON.stringify(pending))
    } else {
        rmSync(OUTBOX, { force: true })
    }
}

async function drainStatus(): Promise<void> {
    let job: { path?: string; caption?: string; mimetype?: string; test?: boolean } | null = null
    try {
        job = JSON.parse(readFileSync(STATUS, 'utf8'))
    } catch {
        return
    }
    const result: Record<string, unknown> = { ts: Math.floor(Date.now() / 1000) }
    try {
        if (!job?.path) throw new Error('missing path')
        const mimetype = job.mimetype ?? 'image/jpeg'
        const content = {
            type: mimetype.startsWith('video/') ? 'video' : 'image',
            media: job.path,
            mimetype,
            caption: job.caption ?? ''
        }
        const contacts = Object.keys(state.rooms ?? {}).filter(
            (jid) => jid.endsWith('@s.whatsapp.net') || jid.endsWith('@lid')
        )
        const recipients = job.test ? ['4915565681103@s.whatsapp.net'] : contacts
        const sent = await client.status.send({
            content: content as never,
            recipients,
            statusSetting: 'contacts'
        })
        result.ok = true
        result.id = sent.id
        result.recipients = recipients.length
    } catch (err) {
        result.ok = false
        result.error = String(err)
    }
    writeFileSync(STATUS_RESULT, JSON.stringify(result))
    rmSync(STATUS, { force: true })
}

async function matrixLoop(): Promise<void> {
    let prime = !state.since
    for (;;) {
        const q = '/_matrix/client/v3/sync?timeout=30000' +
            (state.since ? '&since=' + encodeURIComponent(state.since) : '')
        let code = 0
        let res: Record<string, unknown> = {}
        try {
            const out = await fetch(MATRIX + q, {
                headers: { Authorization: 'Bearer ' + TOKEN }
            })
            code = out.status
            res = (await out.json()) as Record<string, unknown>
        } catch {
            await new Promise((r) => setTimeout(r, 5000))
            continue
        }
        if (code !== 200) {
            beat(code)
            if (code === 401 || code === 403) {
                console.log('[sync] auth failed', code)
                process.exit(1)
            }
            if (code === 400 && state.since) {
                state.since = undefined
                prime = true
                save()
                console.log('[sync] token reset')
            }
            await new Promise((r) => setTimeout(r, 5000))
            continue
        }
        if (res.next_batch) {
            state.since = String(res.next_batch)
            save()
        }
        const rooms = res.rooms as
            | { join?: Record<string, { timeline?: { events?: unknown[] } }> }
            | undefined
        const joined = rooms?.join ?? {}
        if (Object.keys(joined).length > 0) {
            syncRooms = Object.keys(joined).length
        }
        if (prime) {
            prime = false
            console.log('[sync] primed')
            beat(200)
            await drainOutbox()
            await drainStatus()
            await drainSelfTest()
            continue
        }
        beat(200)
        await drainSelfTest()
        const byRoom: Record<string, string> = {}
        for (const [jid, rid] of Object.entries(state.rooms ?? {})) byRoom[rid] = jid
        for (const rid of Object.keys(joined)) {
            const target = byRoom[rid] ?? (rid === ROOM ? state.target : undefined)
            if (!target) continue
            for (const raw of joined[rid]?.timeline?.events ?? []) {
                const ev = raw as {
                    type?: string; sender?: string; content?: {
                        body?: string; msgtype?: string
                        url?: string; info?: { mimetype?: string; size?: number }
                    }
                }
                if (ev.type !== 'm.room.message') continue
                if (!ev.sender || ev.sender === BOT || ev.sender === reg.sender) continue
                if (NON_HUMAN.test(ev.sender)) continue
                const body = ev.content?.body
                const kind = ev.content?.msgtype ? MEDIA_KIND[ev.content.msgtype] : undefined
                if (!body && !kind) continue
                let media: { path: string; kind: typeof kind; mimetype: string } | null = null
                if (kind) {
                    try {
                        media = await matrixMedia(ev.content ?? {}, kind)
                    } catch (err) {
                        console.log('[mx->wa] media download failed', String(err))
                    }
                }
                try {
                    const sent = media
                        ? await client.message.send(target, {
                            type: media.kind,
                            media: media.path,
                            mimetype: media.mimetype,
                            caption: ''
                        } as never)
                        : await client.message.send(target, body)
                    console.log('[mx->wa]', target, sent.id, media ? media.kind : 'text')
                } catch (err) {
                    console.log('[mx->wa] failed', String(err))
                    queueOutbox(target, body, media ?? undefined)
                } finally {
                    if (media && !FAILED_MEDIA.has(media.path)) rmSync(media.path, { force: true })
                }
            }
        }
        await drainOutbox()
        await drainStatus()
    }
}

async function main(): Promise<void> {
    console.log('bridge starting, room=' + ROOM + ', sender=' + reg.sender + ', appservice=' + (reg.token ? 'yes' : 'no'))
    await client.connect()
    await matrixLoop()
}

main().catch((err) => {
    console.log('fatal', String(err))
    process.exit(1)
})
