import { NextResponse } from 'next/server';
import { authSession } from "@/lib/auth/session-server";
import { query } from '@/lib/db-postgres';

const GITEA_API_URL = process.env.GITEA_API_URL ?? 'https://git.vibnai.com';
const GITEA_API_TOKEN = process.env.GITEA_API_TOKEN ?? '';

async function giteaGet(path: string) {
  const res = await fetch(`${GITEA_API_URL}/api/v1${path}`, {
    headers: { Authorization: `token ${GITEA_API_TOKEN}` },
    next: { revalidate: 30 },
  });
  if (!res.ok) throw new Error(`Gitea ${res.status}: ${path}`);
  return res.json();
}

/**
 * GET — returns the project's apps/ directories from Gitea + saved designPackages.
 * Response: { apps: [{ name, path, type }], designPackages: { appName: packageId } }
 */
export async function GET(
  _req: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  const { projectId } = await params;

  const session = await authSession();
  if (!session?.user?.email) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const rows = await query<{ data: Record<string, unknown> }>(
    `SELECT p.data FROM fs_projects p
     JOIN fs_users u ON u.id = p.user_id
     WHERE p.id = $1 AND u.data->>'email' = $2 LIMIT 1`,
    [projectId, session.user.email]
  );

  if (rows.length === 0) {
    return NextResponse.json({ error: 'Project not found' }, { status: 404 });
  }

  const data = rows[0].data ?? {};
  const giteaRepo = data.giteaRepo as string | undefined; // e.g. "mark/sportsy"
  const designPackages = (data.designPackages ?? {}) as Record<string, string>;

  let apps: { name: string; path: string }[] = [];

  if (giteaRepo) {
    // First: try the standard turborepo apps/ directory
    try {
      const contents: Array<{ name: string; path: string; type: string }> =
        await giteaGet(`/repos/${giteaRepo}/contents/apps`);
      apps = contents
        .filter((item) => item.type === 'dir')
        .map(({ name, path }) => ({ name, path }));
    } catch {
      // No apps/ dir — fall through to import detection below
    }

    // Fallback: no apps/ dir — scan repo root for deployable components.
    // Works for any project structure (imported, single-repo, monorepo variants).
    if (apps.length === 0) {
      try {
        // Try CODEBASE_MAP.md first (written by ImportAnalyzer for imported repos)
        const mapFile = await giteaGet(`/repos/${giteaRepo}/contents/CODEBASE_MAP.md`).catch(() => null);
        if (mapFile?.content) {
          const decoded = Buffer.from(mapFile.content, 'base64').toString('utf-8');
          const matches = [...decoded.matchAll(/###\s+.+?[—–-]\s+[`]?([^`\n(]+)[`]?/g)];
          const parsedApps = matches
            .map(m => m[1].trim().replace(/^`|`$/g, '').replace(/\/$/, ''))
            .filter(p => p && p.length > 0 && !p.includes(' ') && !p.startsWith('http') && p !== '.')
            .map(p => ({ name: p.split('/').pop() ?? p, path: p }));
          if (parsedApps.length > 0) apps = parsedApps;
        }
      } catch { /* CODEBASE_MAP not available */ }

      // Scan top-level dirs for app signals
      if (apps.length === 0) {
        try {
          const SKIP = new Set(['docs', 'scripts', 'keys', '.github', 'node_modules', '.git', 'dist', 'build', 'coverage']);
          const APP_SIGNALS = ['package.json', 'requirements.txt', 'pyproject.toml', 'Dockerfile', 'next.config.ts', 'next.config.js', 'vite.config.ts', 'main.py', 'app.py', 'index.js', 'server.ts'];

          const root: Array<{ name: string; path: string; type: string }> =
            await giteaGet(`/repos/${giteaRepo}/contents/`);

          // Check if the root itself is an app (single-repo projects)
          const rootIsApp = root.some(f => f.type === 'file' && APP_SIGNALS.includes(f.name));
          if (rootIsApp) {
            // Repo root is the app — use repo name as label, empty string as path
            apps = [{ name: giteaRepo.split('/').pop() ?? 'app', path: '' }];
          } else {
            // Scan subdirs
            const dirs = root.filter(i => i.type === 'dir' && !SKIP.has(i.name));
            const candidates = await Promise.all(
              dirs.map(async (dir) => {
                try {
                  const sub: Array<{ name: string; type: string }> = await giteaGet(`/repos/${giteaRepo}/contents/${dir.path}`);
                  return sub.some(f => APP_SIGNALS.includes(f.name)) ? { name: dir.name, path: dir.path } : null;
                } catch { return null; }
              })
            );
            apps = candidates.filter((a): a is { name: string; path: string } => a !== null);
          }
        } catch { /* scan failed */ }
      }

      // Last resort: expose the repo root so the file tree still works
      if (apps.length === 0) {
        apps = [{ name: giteaRepo.split('/').pop() ?? 'app', path: '' }];
      }
    }
  }

  return NextResponse.json({ apps, designPackages, giteaRepo, isImport: !!(data.isImport || data.creationMode === 'migration') });
}

/**
 * PATCH — saves { appName, packageId } → stored in fs_projects.data.designPackages
 */
export async function PATCH(
  req: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  const { projectId } = await params;

  const session = await authSession();
  if (!session?.user?.email) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const { appName, packageId } = await req.json() as { appName: string; packageId: string };

  if (!appName || !packageId) {
    return NextResponse.json({ error: 'appName and packageId are required' }, { status: 400 });
  }

  await query(
    `UPDATE fs_projects p
     SET data = data || jsonb_build_object(
       'designPackages',
       COALESCE(data->'designPackages', '{}'::jsonb) || jsonb_build_object($3, $4)
     ),
     updated_at = NOW()
     FROM fs_users u
     WHERE p.id = $1 AND p.user_id = u.id AND u.data->>'email' = $2`,
    [projectId, session.user.email, appName, packageId]
  );

  return NextResponse.json({ success: true });
}
