import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

import TraceFiltersSidebar from '@/layout/sidebar/TraceFiltersSidebar.vue'
import NodeFiltersSidebar from '@/layout/sidebar/NodeFiltersSidebar.vue'
import { inIframe } from '@/utils/navigation'
import TraceList from '@/views/trace-list/TraceList.vue'
import TraceView from '@/views/trace-view/TraceView.vue'

// -----------------------------------------------------------------------------
// Dynamic base path detection for embedded/standalone modes
// -----------------------------------------------------------------------------

function getBase(): string {
  if (inIframe()) {
    const pathName = window.location.pathname

    if (pathName.includes('/dip/')) {
      // in iframe inside Dataiku
      return '/dip/api/webapps/view'
    } else {
      // in iframe but not in Dataiku - use current pathname
      return pathName.endsWith('/') ? pathName : `${pathName}/`
    }
  } else {
    // outside iframe
    let location = window.location.pathname.match(
      /(\/public-webapps\/[a-zA-Z0-9\-_]*\/[a-zA-Z0-9\-_]*).*/,
    )

    if (location) {
      // running as public-webapp
      return `${location[1]}/`
    } else {
      // check if running as webapp
      location = window.location.pathname.match(/(\/webapps\/[a-zA-Z0-9\-_]*\/[a-zA-Z0-9\-_]*).*/)
    }

    // either webapp or standalone (no path match)
    return location ? `${location[1]}/` : '/'
  }
}

function pickHistory() {
  const base = getBase()
  // use web history if pathname matches base, otherwise fall back to hash history
  // (hash history works better for DSS iframe where query params are in the URL)
  return window.location.pathname.startsWith(base)
    ? createWebHistory(base)
    : createWebHashHistory(base)
}

// -----------------------------------------------------------------------------
// Router configuration
// -----------------------------------------------------------------------------

const router = createRouter({
  history: pickHistory(),
  routes: [
    {
      path: '/',
      name: 'traceList',
      components: {
        main: TraceList,
        sidebarContent: TraceFiltersSidebar,
      },
    },
    {
      path: '/traces/:traceId',
      name: 'trace',
      components: {
        main: TraceView,
        sidebarContent: NodeFiltersSidebar,
      },
    },
    {
      path: '/traces/:traceId/nodes/:nodeId',
      name: 'node',
      components: {
        main: TraceView,
        sidebarContent: NodeFiltersSidebar,
      },
    },
  ],
})

export default router
