<script setup lang="ts">
definePageMeta({ layout: false });
const route = useRoute();
const topicId = route.params.id as string;

const { data: lesson, pending, error } = useAsyncData(
  `lesson-dl-${topicId}`,
  () => $fetch<any>(`/api/topics/${topicId}/lesson`)
);

watch(lesson, (val) => {
  if (!val) return;

  const content = val.content ?? {};
  const steps = (content.steps ?? []).map((step: any) => {
    const { audioPath, audioChunks, questionAudioPath, questionAudioChunks, optionAudioPaths, ...rest } = step;
    return rest;
  });

  const payload = {
    lessonId: val.id,
    topicId,
    keyConcepts: content.keyConcepts ?? [],
    analogiesUsed: content.analogiesUsed ?? [],
    steps,
  };

  const blob = new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `lesson-${topicId.slice(0, 8)}.json`;
  a.click();
  URL.revokeObjectURL(url);
}, { immediate: true });
</script>

<template>
  <div style="font-family:monospace;padding:2rem;color:#666;">
    <p v-if="pending">Loading…</p>
    <p v-else-if="error">Error loading lesson.</p>
    <p v-else>Download started. <a :href="`/learn/${topicId}`" style="color:#6366F1;">← Back to lesson</a></p>
  </div>
</template>
