import { register } from 'ts-node-maintained'
import typescript from '@rollup/plugin-typescript'
import ts from 'typescript'
import resolve from '@rollup/plugin-node-resolve'
import { fromRollup } from '@web/dev-server-rollup'
import { OAuth2Server } from 'oauth2-mock-server'
// Using the core library here slows down loading time significantly
import getPort, { portNumbers } from 'get-port'

const typescriptPlugin = fromRollup(typescript, {}, {})
const resolvePlugin = fromRollup(resolve, {}, {})

register({
  transpileOnly: true, // Optional: Skips type checking for faster compilation
  esm: true, // Enables ES module support
})

const oauth2server = new OAuth2Server()
let oauth2env

/** @typedef {import('@web/test-runner').TestRunnerConfig} TestRunnerConfig */

const filteredLogs = ['Running in dev mode', 'lit-html is in dev mode', 'Lit is in dev mode']

export default /** @type TestRunnerConfig */ ({
  nodeResolve: false,
  files: ['test/**/*.test.ts', 'test/**/*.spec.ts'],
  // files: ['test/core/fragment_manager.spec.ts'],

  concurrentBrowsers: 3,

  /** Filter out lit dev mode logs */
  filterBrowserLogs(log) {
    for (const arg of log.args) {
      if (typeof arg === 'string' && filteredLogs.some((l) => arg.includes(l))) {
        return false
      }
    }
    return true
  },

  plugins: [
    {
      name: 'mock-api',
      serve(context) {
        if (context.path === '/test/env.js') {
          const data = {
            oauth2: oauth2env,
          }
          return `export default ${JSON.stringify(data)}`
        }
        return undefined
      },
    },

    resolvePlugin({ browser: true }),

    typescriptPlugin({
      tsconfig: 'tsconfig.testing.json',
      typescript: ts,
      compilerOptions: {
        sourceMap: true,
      },
    }),

    {
      name: 'servers',
      async serverStart() {
        const port = await getPort({ port: portNumbers(8000, 8100) })
        const jwtKey = await oauth2server.issuer.keys.generate('RS256')
        await oauth2server.start(port, 'localhost')
        oauth2env = {
          port,
          jwtKey,
          issuer: oauth2server.issuer.url,
        }
      },

      async serverStop() {
        await oauth2server.stop()
      },
    },
  ],

  testRunnerHtml: (testFramework) =>
    `<html class="theme-light">
    <head>
      <link rel="stylesheet" href="/test/visualization/lib/test-styles.css" />
      <!-- m3 styles -->
      <link rel="stylesheet" href="/src/styles/m3/tokens.css" data-theme="tokens" />
      <link rel="stylesheet" href="/src/styles/m3/theme.css" data-theme="light" />
    </head>
    <body>
      <script type="module" src="${testFramework}"></script>
    </body>
  </html>`,

  testFramework: {
    config: {
      timeout: 60000,
    },
  },
  browserStartTimeout: 20000,
  testsStartTimeout: 20000,
  testsFinishTimeout: 60000,
})
