// ZIP Export/Import: Stück mit Noten + Annotations als .zip exportieren/importieren

async function exportPieceZip(piece, annotations) {
  const zip = new JSZip();

  // Manifest mit Metadaten
  zip.file('manifest.json', JSON.stringify({
    version: 1,
    title: piece.title,
    composer: piece.composer || '',
    kind: piece.kind,
    exportedAt: Date.now(),
  }, null, 2));

  // Annotations
  zip.file('annotations.json', JSON.stringify(annotations, null, 2));

  // PDF-Datei vom Server holen (falls vorhanden)
  if (piece.kind === 'pdf' && piece.pdfFilename) {
    try {
      const res = await fetch('/api/uploads/' + piece.pdfFilename);
      if (res.ok) {
        const blob = await res.blob();
        zip.file('score.pdf', blob);
      }
    } catch (err) {
      console.error('PDF fetch for export failed:', err);
    }
  }

  // Demo-SVG mitspeichern
  if (piece.kind === 'demo') {
    try {
      const res = await fetch('demo-score.svg');
      if (res.ok) {
        const text = await res.text();
        zip.file('demo-score.svg', text);
      }
    } catch (err) {
      console.error('SVG fetch for export failed:', err);
    }
  }

  // ZIP erzeugen + Download
  const blob = await zip.generateAsync({ type: 'blob' });
  const filename = (piece.title || 'stueck').replace(/[^a-zA-Z0-9äöüÄÖÜß\-_ ]/g, '') + '.4v.zip';
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

async function importPieceZip(file) {
  const zip = await JSZip.loadAsync(file);

  // Manifest lesen
  const manifestFile = zip.file('manifest.json');
  if (!manifestFile) throw new Error('Ungültige Datei: manifest.json fehlt.');
  const manifest = JSON.parse(await manifestFile.async('text'));

  // Annotations lesen
  const annFile = zip.file('annotations.json');
  const annotations = annFile ? JSON.parse(await annFile.async('text')) : { strokes: [], pins: [], stamps: [], checklist: {}, rehearsals: [] };

  let piece;

  // PDF hochladen falls vorhanden
  const pdfFile = zip.file('score.pdf');
  if (pdfFile && manifest.kind === 'pdf') {
    const pdfBlob = await pdfFile.async('blob');
    const pdfFileObj = new File([pdfBlob], (manifest.title || 'import') + '.pdf', { type: 'application/pdf' });
    const result = await window.apiUploadPiece(pdfFileObj);
    if (!result.ok) throw new Error(result.error || 'Upload fehlgeschlagen.');
    piece = result.piece;
    // Titel + Composer aus Manifest übernehmen
    await window.apiUpdatePiece(piece.id, { title: manifest.title, composer: manifest.composer });
    piece.title = manifest.title;
    piece.composer = manifest.composer;
  } else {
    // Demo oder Stück ohne PDF
    const res = await fetch('/api/pieces', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({
        title: manifest.title,
        composer: manifest.composer,
        kind: manifest.kind || 'demo',
      }),
    });
    const result = await res.json();
    if (!result.ok) throw new Error(result.error || 'Stück anlegen fehlgeschlagen.');
    piece = result.piece;
  }

  // Annotations speichern
  await window.apiSaveAnnotations(piece.id, annotations);

  return { piece, annotations };
}

window.exportPieceZip = exportPieceZip;
window.importPieceZip = importPieceZip;
