import {defineConfig} from 'vite';
import path from "path";
import fs from "fs";

export default defineConfig({
  root: '.',
  server: {
    fs: {strict: false},
  },
  plugins: [
    {
      name: 'print-preview-url',
      configureServer(server) {
        server.httpServer?.once('listening', () => {
          const baseUrl = `http://localhost:${server.config.server.port || 5173}`;
          console.log("Preview URL: ", baseUrl + '/preview/sections/preview.html\n');
          console.log('🛑 Press Ctrl+C to stop the local server 🛑\n');
        });
      },
    },
    {
      name: 'no-vite-cache',
      configureServer(server) {
        // use process.cwd() for analytics path
        const analyticsDir = path.resolve(process.cwd(), 'preview', 'shared')
        const analyticsFile = path.resolve(analyticsDir, 'analytics.json')

        // ensure analytics folder & file exist
        fs.mkdirSync(analyticsDir, {recursive: true})
        if (!fs.existsSync(analyticsFile)) {
          fs.writeFileSync(analyticsFile, JSON.stringify({}, null, 2), 'utf-8')
        }

        // helper to bump and persist counter for a given section
        function bumpSectionCount(section) {
          const raw = fs.readFileSync(analyticsFile, 'utf-8')
          const data = JSON.parse(raw)
          const next = (data[section] || 0) + 1
          data[section] = next
          fs.writeFileSync(analyticsFile, JSON.stringify(data, null, 2), 'utf-8')
          return next
        }

        server.middlewares.use((req, res, next) => {
            const url = req.url || ''

            // cache-bust for any /sections/ URL
            if (url.includes('/sections/')) {
              server.moduleGraph.invalidateAll()
              return next()
            }

            if (url.startsWith('/chosen-section')) {
              // extract "sectionName" from "/chosen-section/<sectionName>"

              const sectionName = req.url.replace(/\/$/, '').split('/').filter(Boolean).pop()
              const newCount = bumpSectionCount(sectionName)

              res.statusCode = 200
              res.setHeader('Content-Type', 'application/json')
              return res.end(JSON.stringify({
                section: sectionName,
                count: newCount
              }))
            }

            // all other requests
            next()
          }
        );
      },
    },
  ],
});
