import type { App } from '@tinyhttp/app';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Determine which frontend directory to use (matches index.ts logic)
const frontendDir = process.env['USE_FRONTEND_BACKUP'] === 'true' ? 'frontend-backup' : 'frontend';

export function setupPluginRoutes(app: App) {
	// Public endpoint - Get list of available plugins
	app.get('/api/plugins', async (_req, res) => {
		try {
			const pluginsDir = path.join(__dirname, '..', '..', frontendDir, 'plugins');

			// Check if plugins directory exists
			if (!fs.existsSync(pluginsDir)) {
				return res.json({ plugins: [] });
			}

			// Read all .js files in plugins directory
			const files = fs.readdirSync(pluginsDir);
			const plugins = files
				.filter(file => file.endsWith('.js') && file !== 'README.md')
				.map(file => ({
					name: file,
					path: `/plugins/${file}`,
					size: fs.statSync(path.join(pluginsDir, file)).size,
					modified: fs.statSync(path.join(pluginsDir, file)).mtime
				}))
				.sort((a, b) => a.name.localeCompare(b.name));

			return res.json({ plugins });
		} catch (error) {
			console.error('Error listing plugins:', error);
			return res.status(500).json({ error: 'Failed to list plugins', status: 500 });
		}
	});
}
