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

// Maps Azure DevOps language names → our sourceLanguages IDs
const AZURE_TO_SCRIBA: Record<string, string> = {
  'COBOL': 'cobol',
  'PL/I': 'pli',
  'PL/SQL': 'oracle',
  'PLSQL': 'oracle',
  'RPG': 'rpg',
  'Natural': 'natural',
  'Fortran': 'fortran',
  'Pascal': 'pascal',
  'Ada': 'ada',
  'Assembly': 'assembly',
  'Clipper': 'clipper',
  'FoxPro': 'clipper',
  'ABAP': 'sap',
  'Visual Basic 6.0': 'vb6',
  'Visual Basic': 'vb6',
  'ColdFusion': 'coldfusion',
  'PowerBuilder': 'powerbuilder',
  'SAS': 'sas',
  'Java': 'java',
  'C#': 'csharp',
  'Python': 'python',
  'JavaScript': 'javascript',
  'TypeScript': 'typescript',
  'PHP': 'php',
  'Ruby': 'ruby',
  'Go': 'go',
  'Rust': 'rust',
  'Swift': 'swift',
  'Kotlin': 'kotlin',
  'Scala': 'scala',
  'C': 'c',
  'C++': 'cpp',
  'Elixir': 'elixir',
  'Haskell': 'haskell',
  'Lua': 'lua',
  'Perl': 'perl',
  'Shell': 'bash',
  'JCL': 'jcl',
  'TSQL': 'db2',
  'SQLPL': 'db2',
  'PLpgSQL': 'oracle',
};

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 account = await db.query.accounts.findFirst({
    where: and(
      eq(schema.accounts.userId, session.user.id),
      eq(schema.accounts.providerId, 'azure')
    ),
  });

  if (!account?.accessToken) return NextResponse.json({ detected: null, breakdown: [] });

  const { searchParams } = new URL(request.url);
  const org = searchParams.get('org');
  const project = searchParams.get('project');
  const repo = searchParams.get('repo');
  if (!org || !project || !repo) return NextResponse.json({ detected: null, breakdown: [] });

  // Azure DevOps API to get repository stats
  const res = await fetch(
    `https://dev.azure.com/${encodeURIComponent(org)}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repo)}/stats?api-version=7.0`,
    {
      headers: {
        Authorization: `Bearer ${account.accessToken}`,
        Accept: 'application/json',
      },
    }
  );

  if (!res.ok) return NextResponse.json({ detected: null, breakdown: [] });

  const data = await res.json();
  
  // Azure DevOps returns language breakdown in the stats
  // The structure may vary, so we'll handle it accordingly
  const languages: Record<string, number> = data.branches?.[0]?.commit?.tree?.entries?.reduce(
    (acc: Record<string, number>, entry: any) => {
      if (entry.path && entry.path.includes('.')) {
        const ext = entry.path.split('.').pop()?.toLowerCase();
        if (ext) {
          // Map extension to language name (simplified)
          const langMap: Record<string, string> = {
            'cob': 'COBOL',
            'cbl': 'COBOL',
            'pli': 'PL/I',
            'pl1': 'PL/I',
            'rpg': 'RPG',
            'rpgle': 'RPG',
            'for': 'Fortran',
            'f90': 'Fortran',
            'pas': 'Pascal',
            'pp': 'Pascal',
            'ada': 'Ada',
            'asm': 'Assembly',
            's': 'Assembly',
            'vb': 'Visual Basic',
            'cls': 'Visual Basic',
            'cfm': 'ColdFusion',
            'cfc': 'ColdFusion',
            'java': 'Java',
            'cs': 'C#',
            'py': 'Python',
            'js': 'JavaScript',
            'ts': 'TypeScript',
            'php': 'PHP',
            'rb': 'Ruby',
            'go': 'Go',
            'rs': 'Rust',
            'swift': 'Swift',
            'kt': 'Kotlin',
            'kts': 'Kotlin',
            'scala': 'Scala',
            'sc': 'Scala',
            'c': 'C',
            'h': 'C',
            'cpp': 'C++',
            'cc': 'C++',
            'cxx': 'C++',
            'hpp': 'C++',
            'ex': 'Elixir',
            'exs': 'Elixir',
            'hs': 'Haskell',
            'lhs': 'Haskell',
            'lua': 'Lua',
            'pl': 'Perl',
            'pm': 'Perl',
            'sh': 'Shell',
            'bash': 'Shell',
            'sql': 'PL/SQL',
          };
          const lang = langMap[ext] || ext.toUpperCase();
          acc[lang] = (acc[lang] || 0) + (entry.size || 0);
        }
      }
      return acc;
    },
    {}
  ) || {};

  const total = Object.values(languages).reduce((a, b) => a + b, 0);
  if (total === 0) return NextResponse.json({ detected: null, breakdown: [] });

  const breakdown = Object.entries(languages)
    .sort(([, a], [, b]) => b - a)
    .map(([lang, bytes]) => ({
      name: lang,
      scribaId: AZURE_TO_SCRIBA[lang] ?? null,
      percent: Math.round((bytes / total) * 100),
    }));

  // Best match: first language that maps to a known Scriba ID
  const detected = breakdown.find(b => b.scribaId !== null) ?? null;

  return NextResponse.json({ detected, breakdown });
}
