import * as fs from 'fs';
import * as path from 'path';

function torchlightVitePlugin(options = {}) {
    const { rootFolder = "src", outputPath = "torchlight.gen.ts" } = options;
    const tourIds = new Set();
    return {
        name: "torchlight-vite-plugin",
        configResolved(resolvedConfig) {
        },
        transform(code, id) {
            // Only process TypeScript/TSX files
            if (!id.endsWith(".ts") && !id.endsWith(".tsx")) {
                return null;
            }
            // Skip the generated file itself
            if (id.includes("torchlight.gen.ts")) {
                return null;
            }
            // Simple regex-based extraction for tour IDs
            // This is a simplified version - the TypeScript plugin provides more robust parsing
            const useTorchlightStepsRegex = /useTorchlightSteps\s*\(\s*["']([^"']+)["']/g;
            let match;
            while ((match = useTorchlightStepsRegex.exec(code)) !== null) {
                const tourId = match[1];
                if (tourId && tourId.trim() !== "" && tourId !== "tourId") {
                    tourIds.add(tourId);
                }
            }
            return null;
        },
        generateBundle() {
            const sortedTourIds = Array.from(tourIds).sort();
            if (sortedTourIds.length === 0) {
                return;
            }
            const content = `
      /* eslint-disable */

      // @ts-nocheck

      // noinspection JSUnusedGlobalSymbols
      
      // Auto-generated by torchlight-vite-plugin
// Do not edit this file manually
// Generated on: ${new Date().toISOString()}

declare module "ReactTorchlight" {
  interface TorchlightToursRegistry {
${sortedTourIds.map((id) => `    "${id}": never;`).join("\n")}
  }
}

// Export the tour IDs for runtime use
export const TOUR_IDS = {
${sortedTourIds
                .map((id, index) => `  ${id.replace(/[^a-zA-Z0-9_]/g, "_")}: "${id}"${index < sortedTourIds.length - 1 ? "," : ""}`)
                .join("\n")}
} as const;

export type TourId = ${sortedTourIds.map((id) => `"${id}"`).join(" | ")};
`;
            const outputDir = path.join(rootFolder, path.dirname(outputPath));
            if (!fs.existsSync(outputDir)) {
                fs.mkdirSync(outputDir, { recursive: true });
            }
            fs.writeFileSync(outputPath, content, "utf-8");
            console.log(`✅ Generated torchlight types with ${tourIds.size} tours: ${sortedTourIds.join(", ")}`);
        },
    };
}

export { torchlightVitePlugin };
//# sourceMappingURL=vite.esm.js.map
