import { NextResponse } from 'next/server';
import { execSync } from 'child_process';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

export async function GET() {
    try {
        // First check if version file exists (Docker deployment)
        // Try both /app/version.txt (Docker) and ./version.txt (local)
        const versionPaths = [
            '/app/version.txt',
            join(process.cwd(), 'version.txt')
        ];

        for (const versionFilePath of versionPaths) {
            if (existsSync(versionFilePath)) {
                const version = readFileSync(versionFilePath, 'utf-8').trim();
                if (version && version !== 'unknown' && version !== '') {
                    return NextResponse.json({ version });
                }
            }
        }

        // Fallback: check environment variable
        if (process.env.APP_VERSION) {
            return NextResponse.json({ version: process.env.APP_VERSION });
        }

        // Fallback: check package.json
        try {
            const packageJsonPath = join(process.cwd(), 'package.json');
            if (existsSync(packageJsonPath)) {
                const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
                if (packageJson.version) {
                    return NextResponse.json({ version: `v${packageJson.version}` });
                }
            }
        } catch {
            // Ignore package.json read errors
        }

        // Fallback: try to get from git (local development)
        let version = 'dev';

        try {
            // First try to get the exact tag if we're on a tagged commit
            version = execSync('git describe --tags --exact-match 2>/dev/null', {
                encoding: 'utf-8',
                cwd: process.cwd()
            }).trim();
        } catch {
            try {
                // If not on a tag, get the latest tag with commit info
                version = execSync('git describe --tags --always 2>/dev/null', {
                    encoding: 'utf-8',
                    cwd: process.cwd()
                }).trim();
            } catch {
                // If git is not available or no tags exist, try to get commit hash
                try {
                    const hash = execSync('git rev-parse --short HEAD 2>/dev/null', {
                        encoding: 'utf-8',
                        cwd: process.cwd()
                    }).trim();
                    version = `dev-${hash}`;
                } catch {
                    // Fallback to just 'dev' if git is not available
                    version = 'dev';
                }
            }
        }

        return NextResponse.json({ version });
    } catch (error) {
        console.error('Error getting version:', error);
        return NextResponse.json({ version: 'unknown' });
    }
}
