// auto-split module


async function exportAll() {
    console.log('exportAll START');
    const run = collectRun();
    console.log('collectRun()', run);
    if (!run) {
        alert('Kein Template/keine Steps: bitte Template laden oder Steps anlegen.');
        return;
    }
    if (!checkRequired(run)) {
        console.log('checkRequired() failed');
        return;
    }
    renumberSteps();

    // 1) Push to DocBee using existing function (if token available)
    let pushedDocBee = null;
    try {
        if (window.DOCBEE_TOKEN && window.DOCBEE_TOKEN.length > 10) {
            pushedDocBee = await postToDocBee(true); // variant returning URL
            if (pushedDocBee && typeof pushedDocBee === 'string') {
                run.docbee_url = pushedDocBee;
            }
        }
    } catch (e) {
        console.warn('DocBee push failed:', e);
    }

    // 2) Generate PDF client-side
    const pdfBlob = await generatePdfBlob(run).catch(() => null);

    // 3) Upload to server (DB + PDF)
    const fd = new FormData();
    fd.append('run', JSON.stringify(run));
    if (pdfBlob) fd.append('pdf', pdfBlob, 'report.pdf');

    const res = await fetch('/api/export.php', {
        method: 'POST',
        body: fd
    });
    const raw = await res.text();
    let json;
    try {
        json = JSON.parse(raw);
    } catch {
        json = null;
    }
    console.log('Server response:', raw);
    if (!res.ok || !json || json.ok === false) {
        alert('Serverfehler beim Export:\n' + (json?.error || raw || ('HTTP ' + res.status)));
        return;
    }

    alert('Export fertig:\n' +
        (run.docbee_url ? ('DocBee: ' + run.docbee_url + '\n') : '') +
        (json.pdf_path ? ('PDF gespeichert: ' + json.pdf_path + '\n') : '') +
        ('Report-ID: ' + json.report_id));
}


function exportTemplateYAML() {
    const tpl = collectTemplateFromDOM();
    let yml = '';
    if (window.jsyaml && jsyaml.dump) {
        yml = jsyaml.dump(tpl, {
            lineWidth: 100
        });
    } else {
        yml += `name: "${tpl.name||''}"\n`;
        yml += `module: "${tpl.module||''}"\n`;
        yml += `module_version: "${tpl.module_version||''}"\n`;
        yml += `pbx_version: "${tpl.pbx_version||''}"\n`;
        yml += `olm_nummer: "${tpl.olm_nummer||''}"\n`;
        yml += `steps:\n`;
        tpl.steps.forEach(s => {
            if (s.type === 'group') {
                yml += `  - type: "group"\n`;
                yml += `    title: "${(s.title||'').replace(/"/g,'\\"')}"\n`;
            } else {
                yml += `  - type: "step"\n`;
                yml += `    id: "${s.id||''}"\n`;
                yml += `    title: "${(s.title||'').replace(/"/g,'\\"')}"\n`;
                yml += `    expected: "${(s.expected||'').replace(/"/g,'\\"')}"\n`;
                yml += `    required: ${s.required ? 'true':'false'}\n`;
            }
        });
    }
    const base = `qa-template-${safeName(tpl.module)}-${safeName(tpl.module_version)}-${safeName(tpl.pbx_version)}`;
    download(yml, `${base}.yaml`, 'text/yaml');
}

