/**
 * Telegram bot for OctoCode — ALL commands instant, ALL errors visible.
 * Pre-configured with @Octocode_ai_bot token.
 */

import fs from "fs"
import path from "path"
import os from "os"

const BUILT_IN_TOKEN = "8663765299:AAHJGXXggBbtXdXukiOVyMn_Of2j483nKW8"
const STATUS_FILE = path.join(os.tmpdir(), "octocode-telegram-status")
const MODEL_FILE = path.join(os.tmpdir(), "octocode-telegram-models.json")

function loadConfig() {
  const t = process.env.TELEGRAM_BOT_TOKEN?.trim()
  if (t) return { token: t }
  try {
    const p = path.join(os.homedir(), ".config", "opencode", "telegram.json")
    if (fs.existsSync(p)) {
      const d = JSON.parse(fs.readFileSync(p, "utf-8"))
      if (d.token && d.token !== "YOUR_BOT_TOKEN_HERE") return { token: d.token }
    }
  } catch {}
  return { token: BUILT_IN_TOKEN }
}

let config: any = null
let running = false
let pollOffset = 0
let pollTimer: any = null
let serverApp: any = null
const sessions = new Map<string, { sessionId: string; model: string; lastActive: number }>()
const activeSessions = new Set<string>()
let cachedProviders: any[] = []
let lastProviderFetch = 0

function syncModel(m: string) {
  try {
    let d: any = {}
    if (fs.existsSync(MODEL_FILE)) d = JSON.parse(fs.readFileSync(MODEL_FILE, "utf-8"))
    d.phone = m
    d.phoneTime = Date.now()
    fs.writeFileSync(MODEL_FILE, JSON.stringify(d))
  } catch {}
}

function getModel() {
  try {
    if (!fs.existsSync(MODEL_FILE)) return undefined
    return JSON.parse(fs.readFileSync(MODEL_FILE, "utf-8")).phone
  } catch { return undefined }
}

function readDesktopModel() {
  try {
    if (!fs.existsSync(MODEL_FILE)) return undefined
    return JSON.parse(fs.readFileSync(MODEL_FILE, "utf-8")).desktop
  } catch { return undefined }
}

// === TELEGRAM API ===
async function tg(method: string, body: any = {}): Promise<any> {
  if (!config) throw new Error("No config")
  const c = new AbortController()
  const t = setTimeout(() => c.abort(), 15000)
  try {
    const r = await fetch(`https://api.telegram.org/bot${config.token}/${method}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
      signal: c.signal,
    })
    const d = await r.json()
    if (!d.ok) throw new Error(d.description || "Telegram error")
    return d.result
  } finally { clearTimeout(t) }
}

// === SEND — handles BOTH array and { keyboard: } format ===
async function send(chatId: number, text: string, kb?: any): Promise<string> {
  if (!text) text = "..."
  text = text.length > 4096 ? text.slice(0, 4090) + "..." : text
  const body: any = { chat_id: chatId, text }
  if (kb) {
    const rows = Array.isArray(kb) ? kb : kb.keyboard || kb.inline_keyboard
    if (rows && Array.isArray(rows) && rows.length > 0) {
      body.reply_markup = { inline_keyboard: rows }
    }
  }
  const r = await tg("sendMessage", body)
  return String(r.message_id)
}

// === INTERNAL API ===
async function octoReq(p: string, o: RequestInit = {}): Promise<any> {
  if (!serverApp) throw new Error("Server not running")
  const r = await serverApp.fetch(new Request(`http://localhost${p}`, {
    ...o,
    headers: { "Content-Type": "application/json", ...o.headers as any },
  }))
  if (!r.ok) throw new Error(`HTTP ${r.status}`)
  const t = await r.text()
  return t ? JSON.parse(t) : null
}

function getS(id: string) {
  const s = sessions.get(id)
  if (s && Date.now() - s.lastActive > 86400000) { sessions.delete(id); return undefined }
  return s
}

function setS(id: string, sid: string, m: string) {
  const s = { sessionId: sid, model: m, lastActive: Date.now() }
  sessions.set(id, s)
  return s
}

// === PROVIDER CACHE ===
async function refreshProviders() {
  try {
    const d = await octoReq("/provider")
    const c = new Set(d.connected || [])
    cachedProviders = (d.all || [])
      .filter((p: any) => Object.keys(p.models || {}).length > 0)
      .map((p: any) => ({
        id: p.id,
        name: p.name || p.id,
        models: Object.keys(p.models || {}),
        connected: c.has(p.id),
      }))
    lastProviderFetch = Date.now()
  } catch {}
}

// === KEYBOARDS ===
const MENU = [[{ text: "/models", callback_data: "menu:models" }, { text: "/connect", callback_data: "menu:connect" }]]
const FULL = [...MENU, [{ text: "/sessions", callback_data: "menu:sessions" }]]
const BACK = [[{ text: "← Back", callback_data: "menu:main" }]]

// === COMMANDS ===
async function handleCmd(chatId: number, text: string) {
  const clean = text.replace(/@\w+/g, "").trim()
  const cmd = clean.split(/\s+/)[0].toLowerCase()
  const args = clean.split(/\s+/).slice(1).join(" ")

  switch (cmd) {
    case "/start":
    case "/help":
      await send(chatId, "OctoCode Commands:\n\n/new — Fresh session\n/status — Session info\n/model — Switch model\n/models — Browse models\n/connect — Browse providers\n/sessions — Browse sessions\n/stop — Stop agent", FULL)
      return

    case "/new": {
      const cs = String(chatId)
      const old = getS(cs)
      if (old?.sessionId) {
        try { await octoReq(`/session/${old.sessionId}/abort`, { method: "POST" }) } catch {}
      }
      sessions.delete(cs)
      await send(chatId, "Session reset. Send a message to start fresh.", MENU)
      return
    }

    case "/status": {
      const s = getS(String(chatId))
      const desktopModel = readDesktopModel()
      let msg = s ? `Session: ${s.sessionId}\nModel: ${s.model}` : "No active session."
      if (desktopModel) msg += `\nDesktop model: ${desktopModel}`
      await send(chatId, msg, MENU)
      return
    }

    case "/stop": {
      const cs = String(chatId)
      const s = getS(cs)
      if (s?.sessionId) {
        try {
          await octoReq(`/session/${s.sessionId}/abort`, { method: "POST" })
          activeSessions.delete(cs)
          await send(chatId, "Agent stopped.", MENU)
        } catch (e: any) {
          await send(chatId, `Stop failed: ${e.message}`)
        }
      } else {
        // Try to stop any active session for this chat
        await send(chatId, "No active session to stop.", MENU)
      }
      return
    }

    case "/model": {
      if (!args) {
        const current = getModel() ?? getS(String(chatId))?.model ?? "google/gemini-2.5-flash"
        await send(chatId, `Current model: ${current}\n\nUse /models to browse, or /model <provider/model> to set.`, MENU)
        return
      }
      const s = getS(String(chatId))
      if (s) { s.model = args; s.lastActive = Date.now() } else setS(String(chatId), "", args)
      syncModel(args)
      await send(chatId, `Model set: ${args}`, MENU)
      return
    }

    case "/models": {
      if (!cachedProviders.length || Date.now() - lastProviderFetch > 60000) await refreshProviders()
      if (!cachedProviders.length) {
        await send(chatId, "No providers available. Use /connect to add one.", MENU)
        return
      }
      const kb = cachedProviders.map(p => [
        { text: `${p.connected ? "●" : "○"} ${p.name} (${p.models.length})`, callback_data: `models:${p.id}` }
      ])
      kb.push([{ text: "← Back", callback_data: "menu:main" }])
      await send(chatId, "Select a provider:", kb)
      return
    }

    case "/connect": {
      if (!cachedProviders.length || Date.now() - lastProviderFetch > 60000) await refreshProviders()
      const kb = cachedProviders.map(p => [
        { text: `${p.connected ? "●" : "○"} ${p.name}`, callback_data: `conn:${p.id}` }
      ])
      kb.push([{ text: "← Back", callback_data: "menu:main" }])
      await send(chatId, "Providers:", kb)
      return
    }

    case "/sessions": {
      await showSessions(chatId, 0)
      return
    }

    default:
      await send(chatId, `Unknown command: ${cmd}\n\nType /help for available commands.`, MENU)
  }
}

// === SESSIONS LIST ===
async function showSessions(chatId: number, off: number) {
  try {
    const d = await octoReq(`/session?limit=30&start=${Date.now() - 2592000000}`)
    if (!d?.length) {
      await send(chatId, "No sessions found.", BACK)
      return
    }
    const sorted = d
      .filter((x: any) => !x.parentID)
      .sort((a: any, b: any) => b.time.updated - a.time.updated)
    const pg = sorted.slice(off, off + 10)
    if (!pg.length) {
      await send(chatId, "No more sessions.", BACK)
      return
    }
    const kb = pg.map((x: any) => [
      { text: `${(x.title || "?").substring(0, 30)} (${new Date(x.time.updated).toLocaleDateString()})`, callback_data: `sess:${x.id}` }
    ])
    const nav: any[] = []
    if (off > 0) nav.push({ text: "← Prev", callback_data: `sesspage:${Math.max(0, off - 10)}` })
    if (off + 10 < sorted.length) nav.push({ text: "More →", callback_data: `sesspage:${off + 10}` })
    if (nav.length) kb.push(nav)
    kb.push([{ text: "← Back", callback_data: "menu:main" }])
    await send(chatId, `Sessions (${off + 1}–${Math.min(off + 10, sorted.length)}/${sorted.length}):`, kb)
  } catch (e: any) {
    await send(chatId, `Error loading sessions: ${e.message}`)
  }
}

// === CALLBACKS ===
async function handleCb(chatId: number, data: string) {
  const parts = data.split(":")
  const action = parts[0]
  const payload = parts.slice(1).join(":")

  try {
    switch (action) {
      case "menu:main": {
        const kb = [MENU[0], [{ text: "/sessions", callback_data: "menu:sessions" }], [{ text: "/help", callback_data: "menu:help" }]]
        await send(chatId, "OctoCode Live", kb)
        return
      }
      case "menu:models": {
        if (!cachedProviders.length || Date.now() - lastProviderFetch > 60000) await refreshProviders()
        if (!cachedProviders.length) {
          await send(chatId, "No providers available.", BACK)
          return
        }
        const kb = cachedProviders.map(p => [
          { text: `${p.connected ? "●" : "○"} ${p.name} (${p.models.length})`, callback_data: `models:${p.id}` }
        ])
        kb.push([{ text: "← Back", callback_data: "menu:main" }])
        await send(chatId, "Select a provider:", kb)
        return
      }
      case "menu:connect": {
        if (!cachedProviders.length || Date.now() - lastProviderFetch > 60000) await refreshProviders()
        const kb = cachedProviders.map(p => [
          { text: `${p.connected ? "●" : "○"} ${p.name}`, callback_data: `conn:${p.id}` }
        ])
        kb.push([{ text: "← Back", callback_data: "menu:main" }])
        await send(chatId, "Providers:", kb)
        return
      }
      case "menu:sessions": {
        await showSessions(chatId, 0)
        return
      }
      case "menu:help": {
        await send(chatId, "OctoCode Commands:\n\n/new — Fresh session\n/status — Session info\n/model — Switch model\n/models — Browse models\n/connect — Browse providers\n/sessions — Browse sessions\n/stop — Stop agent")
        return
      }
      case "models": {
        const pid = payload
        const p = cachedProviders.find(x => x.id === pid)
        if (!p) {
          await send(chatId, "Provider not found.")
          return
        }
        const kb = p.models.map(m => [{ text: m, callback_data: `sel:${pid}/${m}` }])
        kb.push([{ text: "← Back", callback_data: "menu:models" }])
        await send(chatId, `${p.name} — Select model:`, kb)
        return
      }
      case "sel": {
        const cs = String(chatId)
        const modelPath = payload
        const s = getS(cs)
        if (s) { s.model = modelPath; s.lastActive = Date.now() } else setS(cs, "", modelPath)
        syncModel(modelPath)
        await send(chatId, `Model: ${modelPath}`, MENU)
        return
      }
      case "sesspage": {
        const off = parseInt(payload) || 0
        await showSessions(chatId, off)
        return
      }
      case "sess": {
        const sid = payload
        try {
          const d = await octoReq(`/session/${sid}`)
          if (d) {
            const cs = String(chatId)
            const model = d.model || "google/gemini-2.5-flash"
            setS(cs, sid, model)
            syncModel(model)
            await send(chatId, `Switched to: ${d.title || sid}`, MENU)
          } else {
            await send(chatId, "Session not found.")
          }
        } catch {
          await send(chatId, "Error loading session.")
        }
        return
      }
      case "conn": {
        const pid = payload
        await send(chatId, `${pid}: Use the /connect command in terminal to toggle.`, [[{ text: "/connect", callback_data: "menu:connect" }]])
        return
      }
      case "stop": {
        const sid = payload
        try {
          await octoReq(`/session/${sid}/abort`, { method: "POST" })
          activeSessions.delete(String(chatId))
          await send(chatId, "Agent stopped.", MENU)
        } catch {
          await send(chatId, "Failed to stop agent.")
        }
        return
      }
    }
  } catch (e: any) {
    await send(chatId, `Error: ${e.message}`)
  }
}

// === PROCESS AI MESSAGE ===
async function processMsg(chatId: number, text: string) {
  const cs = String(chatId)
  let s = getS(cs)
  const model = getModel() ?? s?.model ?? "google/gemini-2.5-flash"

  // Create session if needed
  if (!s?.sessionId) {
    try {
      const r = await octoReq("/session", { method: "POST", body: JSON.stringify({ title: `TG ${cs}` }) })
      s = setS(cs, r.id, model)
    } catch (e: any) {
      await send(chatId, `Error creating session: ${e.message}`)
      return
    }
  }

  const [pid, ...mp] = model.split("/")
  const mid = mp.join("/")
  activeSessions.add(cs)
  const stopKB = [[{ text: "⏹ Stop", callback_data: `stop:${s.sessionId}` }]]

  // Typing indicator
  const ti = setInterval(() => tg("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => {}), 4000)
  await tg("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => {})

  try {
    await octoReq(`/session/${s.sessionId}/prompt_async`, {
      method: "POST",
      body: JSON.stringify({ parts: [{ type: "text", text }], model: { providerID: pid, modelID: mid } }),
    })
    await pollResp(chatId, s.sessionId, stopKB, MENU)
  } catch (e: any) {
    if (e.message?.includes("409") || e.message?.includes("busy")) {
      try {
        const r = await octoReq("/session", { method: "POST", body: JSON.stringify({ title: `TG ${cs}` }) })
        s = setS(cs, r.id, model)
        await octoReq(`/session/${s.sessionId}/prompt_async`, {
          method: "POST",
          body: JSON.stringify({ parts: [{ type: "text", text }], model: { providerID: pid, modelID: mid } }),
        })
        await pollResp(chatId, s.sessionId, stopKB, MENU)
      } catch {
        await send(chatId, "Agent busy. Try again shortly.")
      }
    } else {
      await send(chatId, `Error: ${e.message}`)
    }
  } finally {
    clearInterval(ti)
    activeSessions.delete(cs)
  }
}

async function pollResp(chatId: number, sid: string, stopKB: any[], menuKB: any[]) {
  const start = Date.now()
  let lastText = ""

  while (Date.now() - start < 180000) {
    await new Promise(r => setTimeout(r, 1500))
    try {
      const msgs = await octoReq(`/session/${sid}/message?limit=5&agent_id=*`)
      if (!msgs?.length) continue
      const assistant = msgs.findLast((x: any) => x.info?.role === "assistant")
      if (!assistant) continue

      const tp = (assistant.parts || [])
        .filter((p: any) => p.type === "text" && !p.synthetic && !p.ignored)
        .map((p: any) => p.text)
        .join("")

      if (tp && tp !== lastText) lastText = tp

      if (assistant.info.time?.completed) {
        if (lastText) await send(chatId, lastText, menuKB)
        return
      }

      // Show stop button while processing
      if (lastText && (Date.now() - start) % 6000 < 1500) {
        tg("sendChatAction", { chat_id: chatId, action: "typing" }).catch(() => {})
      }
    } catch {}
  }

  if (lastText) await send(chatId, lastText, menuKB)
}

// === POLLING ===
function pollLoop() {
  if (!running || !config) return

  tg("getUpdates", { offset: pollOffset, timeout: 30, allowed_updates: ["message", "callback_query"] })
    .then((ups: any[]) => {
      for (const u of ups) {
        pollOffset = u.update_id + 1
        if (u.message) handleMsg(u.message)
        if (u.callback_query) {
          tg("answerCallbackQuery", { callback_query_id: u.callback_query.id }).catch(() => {})
          if (u.callback_query.message?.chat && u.callback_query.data) {
            handleCb(u.callback_query.message.chat.id, u.callback_query.data)
          }
        }
      }
    })
    .catch(() => {})

  pollTimer = setTimeout(pollLoop, 5000)
  if (pollTimer?.unref) pollTimer.unref()
}

function handleMsg(msg: any) {
  const text = msg.text?.trim()
  if (!text) return
  if (text.startsWith("/")) {
    handleCmd(msg.chat.id, text).catch(() => {})
    return
  }
  processMsg(msg.chat.id, text).catch(() => {})
}

// === TYPE ===
interface TgUpdate { update_id: number; message?: any; callback_query?: any }

// === PUBLIC ===
export async function startTelegramBot(srv: any): Promise<boolean> {
  if (running) return true
  config = loadConfig()
  if (!config) return false

  try {
    const { Server } = await import("../server/server")
    serverApp = Server.Default().app
  } catch {
    serverApp = srv?.app ?? null
  }

  try {
    await tg("getMe")
  } catch {
    config = null
    return false
  }

  running = true
  pollOffset = 0

  try { fs.writeFileSync(STATUS_FILE, JSON.stringify({ running: true })) } catch {}

  // Pre-warm: cache providers (non-blocking)
  refreshProviders().catch(() => {})

  pollLoop()
  return true
}

export function stopTelegramBot() {
  running = false
  if (pollTimer) { clearTimeout(pollTimer); pollTimer = null }
  sessions.clear()
  activeSessions.clear()
  config = null
  try { fs.unlinkSync(STATUS_FILE) } catch {}
}

export function isTelegramBotRunning() { return running }
