/**
 * Main analyzer entry point with dual module support
 */

import { analyzeExpress } from './frameworks/express.js'
import { analyzeNextPages } from './frameworks/nextjs-pages.js'
import { analyzeNextApp } from './frameworks/nextjs-app.js'
import { analyzeVite } from './frameworks/vite.js'
import { analyzeReactRouter } from './frameworks/react-router.js'
import { detectFramework } from './detect.js'
import { exportToJSON } from './export.js'
import { uploadRoutes } from './uploader.js'

export interface AnalyzerOptions {
    projectName: string
    baseUrl?: string
    apiKey?: string
    apiForgeUrl?: string
    upload?: boolean
    saveJson?: boolean
    jsonPath?: string
    framework?: string
    nextDir?: string
    skipInProduction?: boolean
    runOnce?: boolean
}

// Global state for debouncing
const analysisState = new Map<string, { timestamp: number; routes: any[] }>()
const DEBOUNCE_TIME = 5000

/**
 * Main analyze function with auto-detection
 */
export async function analyze(app: any, options: AnalyzerOptions): Promise<any[]> {
    // Skip in production
    if (options.skipInProduction !== false && process.env.NODE_ENV === 'production') {
        console.log('⏭️  Skipping analysis in production')
        return []
    }

    // Debounce check
    if (options.runOnce !== false) {
        const cached = analysisState.get(options.projectName)
        const now = Date.now()

        if (cached && (now - cached.timestamp) < DEBOUNCE_TIME) {
            console.log(`⚡ Analysis skipped - already ran ${Math.round((now - cached.timestamp) / 1000)}s ago`)
            return cached.routes
        }
    }

    console.log(`🔍 Analyzing ${options.projectName}...`)

    // CRITICAL: Prevent restart loops - force saveJson=false when uploading
    if (options.upload !== false && options.apiKey) {
        options.saveJson = false
    }

    let routes: any[] = []
    let framework = options.framework

    // Auto-detect framework if not specified
    if (!framework) {
        const detected = detectFramework(app)
        framework = detected.name
        console.log(`📦 Detected framework: ${framework}`)
    }

    // Analyze based on framework
    switch (framework) {
        case 'express':
            if (!app) {
                console.error('❌ Express app instance required')
                return []
            }
            routes = await analyzeExpress(app)
            break

        case 'nextjs-pages':
            routes = await analyzeNextPages(options.nextDir || 'pages/api')
            break

        case 'nextjs-app':
            routes = await analyzeNextApp(options.nextDir || 'app')
            break

        case 'vite':
            routes = await analyzeVite(options.nextDir || 'vite.config.js')
            break

        case 'react-router':
            routes = await analyzeReactRouter(options.nextDir || 'src/routes.tsx')
            break

        case 'node-http':
        case 'unknown':
        default:
            console.warn(`⚠️  Framework "${framework}" not supported yet`)
            console.log('💡 Supported: express, nextjs-pages, nextjs-app, vite, react-router')
            console.log('💡 Tip: Specify framework manually: { framework: "express" }')
            return []
    }

    console.log(`✅ Found ${routes.length} routes`)

    // Cache results
    if (options.runOnce !== false) {
        analysisState.set(options.projectName, {
            timestamp: Date.now(),
            routes
        })
    }

    // Save JSON (only if not uploading)
    if (options.saveJson) {
        const filePath = options.jsonPath || 'api-export.json'
        await exportToJSON(routes, options.projectName, filePath, options.baseUrl)
    }

    // Upload to APIForge
    if (options.upload !== false && options.apiKey) {
        await uploadRoutes(routes, {
            projectName: options.projectName,
            apiKey: options.apiKey,
            baseUrl: options.baseUrl,
            apiForgeUrl: options.apiForgeUrl,
        })
    }

    return routes
}

// Re-export framework-specific analyzers
export { analyzeExpress, analyzeNextPages, analyzeNextApp, analyzeVite, analyzeReactRouter }
export { exportToJSON } from './export.js'
export { uploadRoutes } from './uploader.js'
export { detectFramework } from './detect.js'

// Default export for CommonJS
export default {
    analyze,
    analyzeExpress,
    analyzeNextPages,
    analyzeNextApp,
    analyzeVite,
    analyzeReactRouter,
    exportToJSON,
    uploadRoutes,
    detectFramework
}
