import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { db, schema } from '@/lib/db';
import { eq, and } from 'drizzle-orm';
import { detectStackViaEngine, fetchGitHubManifests } from '@/lib/repo-manifests';

function parseGitHubUrl(url: string): { owner: string; repo: string } | null {
  const match = url.match(/github\.com\/([^/]+)\/([^/.\s]+)/);
  if (!match) return null;
  return { owner: match[1], repo: match[2] };
}

export async function GET(request: NextRequest) {
  const session = await getSession(request.cookies.get('scriba.access_token')?.value);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const { searchParams } = new URL(request.url);
  const repoUrl = searchParams.get('repoUrl')?.trim();
  const branch = searchParams.get('branch')?.trim() || 'main';
  const sourceLanguage = searchParams.get('sourceLanguage')?.trim().toLowerCase();

  if (!repoUrl) return NextResponse.json({ error: 'repoUrl is required' }, { status: 400 });
  if (!sourceLanguage) return NextResponse.json({ error: 'sourceLanguage is required' }, { status: 400 });

  if (!parseGitHubUrl(repoUrl)) {
    return NextResponse.json(
      { error: 'Stack detection currently supports GitHub repositories only' },
      { status: 400 },
    );
  }

  const ghAccount = await db.query.accounts.findFirst({
    where: and(
      eq(schema.accounts.userId, session.user.id),
      eq(schema.accounts.providerId, 'github'),
    ),
  });
  const token = ghAccount?.accessToken || process.env.GITHUB_TOKEN;

  try {
    const { manifests, filePaths } = await fetchGitHubManifests(repoUrl, branch, sourceLanguage, token);
    if (manifests.length === 0) {
      return NextResponse.json({
        framework: null,
        version: null,
        signals: [],
        message: 'No manifest files found for this language',
      });
    }

    const stack = await detectStackViaEngine(sourceLanguage, manifests, filePaths);
    if (!stack) {
      return NextResponse.json(
        { error: 'Scriba Engine unavailable — start scriba-engine or check SCRIBA_ENGINE_URL' },
        { status: 503 },
      );
    }

    return NextResponse.json(stack);
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    if (msg === 'not_found') {
      return NextResponse.json({ error: 'Repository or branch not found' }, { status: 404 });
    }
    console.error('detect-stack error:', err);
    return NextResponse.json({ error: 'Failed to detect stack' }, { status: 500 });
  }
}
