/**
 * ReportWriterAgent — assembles all step outputs into a FinalIncidentReport
 * with a stable runId and a markdown summary.
 */

import type {
  DispatchDecision,
  TelemetryFindings,
  DiagnosticsSessionResult,
  FinalIncidentReport,
} from '../types.js';

export function writeReport(
  decision: DispatchDecision,
  findings: TelemetryFindings,
  diagResult: DiagnosticsSessionResult | null
): FinalIncidentReport {
  const { runContext, brief } = decision;
  const generatedAt = new Date().toISOString();

  const lines: string[] = [
    `# Incident Report — ${brief.productId}`,
    `**Run ID:** \`${runContext.runId}\``,
    `**Generated:** ${generatedAt}`,
    `**Reported issue:** ${brief.userReport.summary}`,
    brief.userReport.platform ? `**Platform:** ${brief.userReport.platform}` : '',
    brief.userReport.appVersion ? `**App version:** ${brief.userReport.appVersion}` : '',
    '',
    `## Time Window`,
    `- From: ${decision.resolvedTimeWindow.from}`,
    `- To:   ${decision.resolvedTimeWindow.to}`,
    '',
    `## Telemetry Findings (${findings.clusters.length} open cluster${findings.clusters.length !== 1 ? 's' : ''})`,
  ];

  if (findings.queryError) {
    lines.push(`> ⚠️ Telemetry query failed: ${findings.queryError}`);
  } else if (findings.clusters.length === 0) {
    lines.push('No open error clusters found in this time window.');
  } else {
    for (const c of findings.clusters.slice(0, 10)) {
      lines.push(
        `- **[${c.severity.toUpperCase()}]** \`${c.clusterId}\` — ${c.totalCount} events` +
          ` | platform: ${c.platform} | module: ${c.module}` +
          (c.sampleMessage ? ` | "${c.sampleMessage}"` : '')
      );
    }
    if (findings.clusters.length > 10) {
      lines.push(`  … and ${findings.clusters.length - 10} more clusters`);
    }
  }

  lines.push('');
  lines.push('## Top Hypotheses');
  if (findings.topHypotheses.length === 0) {
    lines.push('No hypotheses generated.');
  } else {
    for (const h of findings.topHypotheses) lines.push(`- ${h}`);
  }

  lines.push('');
  lines.push('## Recommended Actions');
  if (findings.recommendedActions.length === 0) {
    lines.push('No actions recommended.');
  } else {
    for (const a of findings.recommendedActions) lines.push(`- ${a}`);
  }

  lines.push('');
  lines.push('## Diagnostics Session');
  if (!diagResult || diagResult.skipped) {
    lines.push(diagResult?.skipReason ? `Skipped: ${diagResult.skipReason}` : 'Not requested.');
  } else if (diagResult.sessionError) {
    lines.push(`> ⚠️ Session creation failed: ${diagResult.sessionError}`);
  } else if (diagResult.session) {
    const s = diagResult.session;
    lines.push(`- **Session ID:** \`${s.id}\``);
    lines.push(`- **Status:** ${s.status}`);
    lines.push(`- **Collection level:** ${s.collectionLevel}`);
    lines.push(`- **Expires:** ${s.expiresAt}`);
    if (s.targetUserId) lines.push(`- **Target user:** ${s.targetUserId}`);
  }

  lines.push('');
  lines.push('---');
  lines.push(`*Generated by ByteLyst A2A incident pipeline · run \`${runContext.runId}\`*`);

  return {
    runId: runContext.runId,
    productId: brief.productId,
    generatedAt,
    summary: brief.userReport.summary,
    clusterCount: findings.clusters.length,
    clusters: findings.clusters,
    topHypotheses: findings.topHypotheses,
    recommendedActions: findings.recommendedActions,
    diagnosticsSession: diagResult?.session ?? null,
    markdownReport: lines.filter(l => l !== '').join('\n'),
  };
}
