import 'dart:convert';

import '../models/klt_models.dart';

class ReportService {
  String markdown(KltAnalysis a) {
    final lines = <String>[];
    lines.add('# KLT 5.1 Lambda Report');
    lines.add('');
    lines.add('- Project: ${a.title}');
    lines.add('- Project ID: ${a.projectId}');
    lines.add('- Generated: ${a.generatedAt.toIso8601String()}');
    lines.add('- CRI: ${a.cri.toStringAsFixed(4)}');
    lines.add('- Average delta: ${a.deltaAvg.toStringAsFixed(4)}');
    lines.add('- MSI max: ${a.msiMax.toStringAsFixed(4)}');
    lines.add('- DI max: ${a.diMax.toStringAsFixed(4)}');
    lines.add('');
    lines.add('## Defects');
    if (a.defects.isEmpty) {
      lines.add('No defects detected.');
    } else {
      for (final d in a.defects) {
        lines.add('- **${d.id} ${d.title}** (${d.defectClass.name}, severity ${d.severity.toStringAsFixed(2)}): ${d.message}');
      }
    }
    lines.add('');
    lines.add('## Lambda values');
    a.lambdaByPix.forEach((id, r) {
      lines.add('- `$id`: lambda=${r.lambda?.toStringAsFixed(5) ?? 'n/a'}, delta=${r.delta?.toStringAsFixed(5) ?? 'n/a'}, auth=${r.auth?.toStringAsFixed(5) ?? 'n/a'}, status=${r.status}');
    });
    lines.add('');
    lines.add('## Legal note');
    lines.add('The KLT 5.1 output is an analytical indicator and does not replace official expert, engineering, audit, legal, or investment conclusions.');
    return lines.join('\n');
  }

  String jsonReport(KltAnalysis a) => const JsonEncoder.withIndent('  ').convert(a.toJson());
}
