import { Bucket, File } from "@google-cloud/storage"

type TFile = {
  name: string
  slug: string
  hidden: boolean
}

export type Exercise = {
  title: string
  slug: string
  graded: boolean
  files: TFile[]
  translations: Record<string, string>
  position: number
}

export type ConfigResponse = {
  config: any
  exercises: Exercise[]
}

/**
 * Crea la configuración y lista de ejercicios para un curso.
 *
 * @param bucket - Instancia de GCS Bucket donde está el curso.
 * @param courseSlug - Slug del curso a procesar.
 * @returns Promise con objeto { config, exercises } listo para usar.
 */
export async function buildConfig(
  bucket: Bucket,
  courseSlug: string
): Promise<ConfigResponse> {
  const prefix = `courses/${courseSlug}/`
  const [files] = await bucket.getFiles({ prefix })

  // 1) Leer learn.json
  const learnFile = files.find(f => f.name.endsWith("learn.json"))!
  const [learnBuf] = await learnFile.download()
  const learnJson = JSON.parse(learnBuf.toString())

  // 2) Agrupar ejercicios
  const map: Record<string, Omit<Exercise, "position">> = {}
  for (const file of files) {
    const parts = file.name.split("/")
    if (!parts.includes("exercises")) continue

    const slug = parts[parts.indexOf("exercises") + 1]
    if (!map[slug]) {
      map[slug] = {
        title: slug,
        slug,
        graded: false,
        files: [],
        translations: {},
      }
    }

    const fname = parts.pop()!
    const m = fname.match(/^readme(?:\.([a-z]{2}))?\.md$/i)
    if (m) {
      const lang = m[1] || "us"
      map[slug].translations[lang] = fname
    } else {
      map[slug].files.push({
        name: fname,
        slug: fname,
        hidden: false,
      })
    }
  }

  const exercises = Object.values(map).map((ex, i) => ({
    ...ex,
    position: i,
  }))

  return {
    config: { ...learnJson },
    exercises,
  }
}
