const EXPECTED_TRACE_SUMMARY = Object.freeze({
  acceptanceCriteria: 52,
  errorCategories: 9,
  featureModules: 13,
  parentFamilies: 89,
  penProductFrames: 18,
  productContracts: 19,
  requirements: 109,
  tasks: 52,
  testCases: 117,
  uiPages: 22,
});

const REQUIRED_UPSTREAM = Object.freeze({
  "TASK-WP7-01": "passed",
  "TASK-WP7-02": "passed",
  "TASK-WP7-03": "deferred_nonblocking_first_version",
  "TASK-WP7-04": "deferred_nonblocking_first_version",
  "TASK-WP7-05": "passed",
});

const shaPattern = /^[0-9a-f]{40}$/i;

export function buildWp706PrefreezeReport({ currentCommit, releaseExists, trace, upstream }) {
  if (releaseExists) throw new Error("WP7_06_RELEASE_WRITTEN_PREMATURELY");
  if (!shaPattern.test(currentCommit ?? "")) throw new Error("WP7_06_CURRENT_COMMIT_INVALID");
  if (trace?.status !== "passed" || !Array.isArray(trace?.errors) || trace.errors.length > 0) {
    throw new Error("WP7_06_TRACE_VALIDATION_FAILED");
  }
  for (const [key, expected] of Object.entries(EXPECTED_TRACE_SUMMARY)) {
    if (trace.summary?.[key] !== expected) throw new Error(`WP7_06_TRACE_COUNT_MISMATCH:${key}`);
  }

  for (const [taskId, expectedStatus] of Object.entries(REQUIRED_UPSTREAM)) {
    const item = upstream?.[taskId];
    if (!item || !shaPattern.test(item.head ?? "")) throw new Error(`WP7_06_UPSTREAM_HEAD_INVALID:${taskId}`);
    if (item.merged !== true) throw new Error(`WP7_06_UPSTREAM_NOT_MERGED:${taskId}`);
    if (item.status !== expectedStatus) throw new Error(`WP7_06_UNSUPPORTED_STATUS:${taskId}`);
  }

  return {
    schema_version: "1.0",
    task_id: "TASK-WP7-06",
    status: "passed",
    current_commit: currentCommit.toLowerCase(),
    release_json_written: false,
    trace_summary: { ...EXPECTED_TRACE_SUMMARY },
    upstream: Object.fromEntries(Object.entries(REQUIRED_UPSTREAM).map(([taskId]) => [taskId, {
      branch: upstream[taskId].branch,
      head: upstream[taskId].head.toLowerCase(),
      merged: true,
      status: upstream[taskId].status,
    }])),
    deferred_external_tasks: Object.entries(REQUIRED_UPSTREAM)
      .filter(([, status]) => status === "deferred_nonblocking_first_version")
      .map(([taskId]) => taskId),
    final_release_allowed: false,
    next_task: "TASK-WP7-07",
  };
}

export { EXPECTED_TRACE_SUMMARY, REQUIRED_UPSTREAM };
