import { mount } from 'svelte'
import App from './App.svelte'
import './app.css'
import { initConfig, setConfig, getConfig, isConfigured } from '$lib/config'

// Dev convenience: `npm run dev` already proxies /api and /agent with
// OIKOS_API_TOKEN baked in server-side (vite.config.ts's authProxy), so the
// SPA's own token only matters for the one route that reads it from a query
// param (config.ts's sseUrl). Auto-fill it here so the "Connect to Oikos"
// prompt doesn't reappear every time localStorage is cleared — only when
// nothing's configured yet, so it never clobbers a deliberate manual
// connection (e.g. pointing dev at a remote server).
function devAutoConfig() {
  if (import.meta.env.DEV && __OIKOS_DEV_TOKEN__ && !isConfigured()) {
    setConfig({ apiUrl: '', token: __OIKOS_DEV_TOKEN__ })
  }
}

function handleDesktopToken() {
  const params = new URLSearchParams(location.search)
  const token = params.get('token')
  if (token && new URLSearchParams(location.search).has('desktop')) {
    const apiUrl = params.get('apiUrl') || getConfig().apiUrl || ''
    setConfig({ apiUrl, token, isDesktop: true })
    initConfig({ apiUrl, token, isDesktop: true })
    params.delete('token')
    const q = params.toString()
    history.replaceState(null, '', location.pathname + (q ? '?' + q : ''))
    return true
  }
  return false
}

function start() {
  initConfig()
  devAutoConfig()
  handleDesktopToken()

  mount(App, { target: document.getElementById('app')! })
}

start()
