import { createReadStream, statSync } from "fs";
import path from "path";
import { Readable } from "stream";

import { NextResponse } from "next/server";

const modelFileMap = {
  "llama-3.2-1b-q4_k_m.gguf": {
    envKey: "COURSEWARE_LAB1_LLAMA_MODEL_PATH",
    fileName: "Llama-3.2-1B.Q4_K_M.gguf",
  },
} as const;

type ModelSlug = keyof typeof modelFileMap;

function resolveModelPath(slug: string) {
  const config = modelFileMap[slug as ModelSlug];
  if (!config) {
    return null;
  }

  const configuredPath = process.env[config.envKey]?.trim();
  if (!configuredPath) {
    return null;
  }

  return {
    absolutePath: path.resolve(configuredPath),
    fileName: config.fileName,
  };
}

export async function GET(
  _request: Request,
  context: { params: Promise<{ filename: string }> },
) {
  const { filename } = await context.params;
  const resolvedFile = resolveModelPath(filename.toLowerCase());

  if (!resolvedFile) {
    return NextResponse.json(
      {
        error: "The requested Lab 1 model file was not found.",
      },
      { status: 404 },
    );
  }

  try {
    const fileStats = statSync(resolvedFile.absolutePath);
    const stream = Readable.toWeb(
      createReadStream(resolvedFile.absolutePath),
    ) as ReadableStream;

    return new NextResponse(stream, {
      headers: {
        "Cache-Control": "private, max-age=0, must-revalidate",
        "Content-Disposition": `attachment; filename="${resolvedFile.fileName}"`,
        "Content-Length": String(fileStats.size),
        "Content-Type": "application/octet-stream",
      },
    });
  } catch {
    return NextResponse.json(
      {
        error: "The requested Lab 1 model file could not be opened.",
      },
      { status: 404 },
    );
  }
}
