import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { logger } from '@/lib/logger';

export interface RouteRequest {
  request_hash: string;          // sha256 of content (never actual content)
  available_backends: string[];  // e.g. ["llama3.1:8b", "qwen3:14b"]
  hardware_tier: string;         // e.g. "rtx4060_8gb"
  privacy_tier: string;          // "personal" | "private" | "external"
  context_length_tokens: number;
  cache_hit: boolean;
}

export interface RouteResponse {
  backend: string;
  confidence: number;
  tier_used: number;    // 0=rule-based, 1=knn, 2=modernbert
  reasoning: string;
}

function extractParamSize(name: string): number {
  const match = name.match(/(\d+)b/i);
  return match ? parseInt(match[1], 10) : 0;
}

/**
 * Rule-based backend selection. Placeholder for future ML tiers.
 *
 * Tier 0 (current): deterministic rule-based routing.
 * Tier 1 (future, #285): kNN embedding router.
 * Tier 2 (future, #285): ModernBERT classifier.
 */
function selectBackend(req: RouteRequest): RouteResponse {
  const backends = req.available_backends;

  if (!backends || backends.length === 0) {
    return {
      backend: 'default',
      confidence: 0.5,
      tier_used: 0,
      reasoning: 'no backends available',
    };
  }

  // Cache hit: any backend works — return first with max confidence
  if (req.cache_hit) {
    return {
      backend: backends[0],
      confidence: 1.0,
      tier_used: 0,
      reasoning: 'cache hit — any backend valid',
    };
  }

  // Long context (>8192 tokens): prefer 70b or 32b model
  if (req.context_length_tokens > 8192) {
    const large = backends.find((b) => b.includes('70b') || b.includes('32b'));
    if (large) {
      return {
        backend: large,
        confidence: 0.85,
        tier_used: 0,
        reasoning: 'long context → large model',
      };
    }
  }

  // Medium context (>4096 tokens): prefer larger model by parameter count
  if (req.context_length_tokens > 4096) {
    const sorted = [...backends].sort((a, b) => extractParamSize(b) - extractParamSize(a));
    return {
      backend: sorted[0],
      confidence: 0.75,
      tier_used: 0,
      reasoning: 'medium context → larger model preferred',
    };
  }

  // Personal privacy tier: prefer smallest/most efficient model
  if (req.privacy_tier === 'personal') {
    const small = backends.find(
      (b) => b.includes('8b') || b.includes('7b') || b.includes('3b'),
    );
    if (small) {
      return {
        backend: small,
        confidence: 0.8,
        tier_used: 0,
        reasoning: 'personal tier → efficient model',
      };
    }
  }

  // Default: first available backend
  return {
    backend: backends[0],
    confidence: 0.7,
    tier_used: 0,
    reasoning: 'rule-based: first available',
  };
}

/**
 * POST /api/route — Cloud router intelligence API.
 *
 * Accepts routing context (no user content — only metadata/hashes) and returns
 * a backend selection with confidence score and reasoning.
 *
 * Auth: Any authenticated user (plan enforcement deferred to future iteration).
 * Privacy: Never stores or logs request content — only hashes and metadata.
 */
export async function POST(request: NextRequest): Promise<NextResponse> {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  let body: RouteRequest;
  try {
    body = (await request.json()) as RouteRequest;
  } catch {
    logger.warn({ action: 'route_invalid_json' }, 'Invalid JSON body in route request');
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
  }

  if (!body.available_backends || body.available_backends.length === 0) {
    return NextResponse.json(
      { error: 'available_backends required' },
      { status: 400 },
    );
  }

  const result = selectBackend(body);
  logger.info(
    { action: 'route_select', user_id: session.user.id, backend: result.backend, confidence: result.confidence },
    'Route decision made',
  );
  return NextResponse.json(result);
}
