#include "workshop_orchestrator_v2/report_builder.hpp"

#include <sstream>

namespace workshop_orchestrator_v2
{

WorkshopReport ReportBuilder::build(
  const WorkshopSession & session,
  const std::vector<StageResultSummary> & stage_results,
  bool overall_success,
  int64_t started_timestamp_us,
  int64_t finished_timestamp_us,
  const std::string & summary) const
{
  WorkshopReport report;
  report.session_id = session.session_id;
  report.overall_success = overall_success;
  report.started_timestamp_us = started_timestamp_us;
  report.finished_timestamp_us = finished_timestamp_us;
  report.stage_results = stage_results;
  report.summary = summary;

  std::string active_parameter_bundle_version;
  uint32_t succeeded_stage_count = 0;
  for (const auto & stage_result : stage_results) {
    report.report_files.insert(
      report.report_files.end(),
      stage_result.artifacts.begin(),
      stage_result.artifacts.end());

    if (stage_result.success) {
      ++succeeded_stage_count;
    }
    if (!stage_result.parameter_version.empty()) {
      active_parameter_bundle_version = stage_result.parameter_version;
    }
  }

  if (overall_success && active_parameter_bundle_version.empty()) {
    active_parameter_bundle_version = session.session_id;
  }

  report.active_parameter_bundle_version = overall_success ? active_parameter_bundle_version : "";

  calibration_common_interfaces::msg::KeyValuePair kv;
  kv.key = "stage_count";
  kv.value = std::to_string(stage_results.size());
  report.metadata.push_back(kv);

  kv.key = "succeeded_stage_count";
  kv.value = std::to_string(succeeded_stage_count);
  report.metadata.push_back(kv);

  kv.key = "failed_stage_count";
  kv.value = std::to_string(stage_results.size() - succeeded_stage_count);
  report.metadata.push_back(kv);

  kv.key = "overall_success";
  kv.value = overall_success ? "true" : "false";
  report.metadata.push_back(kv);

  kv.key = "workshop_line_id";
  kv.value = session.workshop_line_id;
  report.metadata.push_back(kv);

  kv.key = "vehicle_id";
  kv.value = session.vehicle_profile_snapshot.base_info.vehicle_id;
  report.metadata.push_back(kv);

  kv.key = "operator_id";
  kv.value = session.operator_info.operator_id;
  report.metadata.push_back(kv);

  if (!report.active_parameter_bundle_version.empty()) {
    kv.key = "active_parameter_bundle_version";
    kv.value = report.active_parameter_bundle_version;
    report.metadata.push_back(kv);
  }

  if (!stage_results.empty()) {
    kv.key = "last_stage_id";
    kv.value = stage_results.back().stage_id;
    report.metadata.push_back(kv);
  }

  return report;
}

}  // namespace workshop_orchestrator_v2
