import type { RequestStoryV1 } from "@overdeck/report-contract";
import type { FactoryRequestRunLinksResult } from "../adapters/factory";

const WORK_LINK_KINDS = new Set(["factory_run", "phase", "gate", "tool", "change", "log"]);

export function enrichRequestStoryWithFactoryLinks(
  story: RequestStoryV1,
  factoryLinks: FactoryRequestRunLinksResult,
): RequestStoryV1 {
  const existingLinkKeys = new Set(story.links.map((link) => `${link.kind}\0${link.targetSource}\0${link.targetId}`));
  for (const link of factoryLinks.links) {
    const sourceEventId = `request-link:${link.adwId}`;
    const key = `factory_run\0factory-trace\0${link.adwId}`;
    if (!existingLinkKeys.has(key)) {
      story.links.push({
        kind: "factory_run",
        targetSource: "factory-trace",
        targetId: link.adwId,
        occurredAt: link.linkedAt,
        sourceId: "factory-trace",
        sourceEventId,
        ownerUrl: `/factory?run=${encodeURIComponent(link.adwId)}`,
        metadata: {
          ...(link.status ? { status: link.status } : {}),
          ...(link.startedAt ? { startedAt: link.startedAt } : {}),
          ...(link.repo ? { repo: link.repo } : {}),
        },
      });
      existingLinkKeys.add(key);
    }
    if (!story.events.some((event) => event.sourceId === "factory-trace" && event.sourceEventId === sourceEventId)) {
      story.events.push({
        id: `factory-${link.adwId}`,
        requestId: story.requestId,
        kind: "run_linked",
        occurredAt: link.linkedAt,
        recordedAt: link.linkedAt,
        summary: "Work run linked.",
        actor: { type: "machinery", displayName: "Factory" },
        sourceId: "factory-trace",
        sourceEventId,
        producerId: link.adwId,
        payload: {
          runId: link.adwId,
          ...(link.status ? { status: link.status } : {}),
        },
        legacy: false,
      });
    }
  }
  story.events.sort((a, b) => a.occurredAt.localeCompare(b.occurredAt));
  story.links.sort((a, b) => a.occurredAt.localeCompare(b.occurredAt));

  const workCoverage = story.coverage.find((coverage) => coverage.fact === "work_evidence");
  const hasWorkEvidence = story.attachments.length > 0 || story.links.some((link) => WORK_LINK_KINDS.has(link.kind));
  if (workCoverage && hasWorkEvidence) {
    workCoverage.status = "complete";
    workCoverage.sourceId = "request-evidence-links";
    delete workCoverage.reason;
  } else if (workCoverage && !factoryLinks.available) {
    workCoverage.status = "unavailable";
    workCoverage.sourceId = "factory-trace";
    workCoverage.reason = "Exact work-run linkage could not be read.";
  }
  return story;
}
