// TicketExecutionEvidence - Component for displaying latest execution evidence
import React from 'react';

function TicketExecutionEvidence({ ticket }) {
  if (!ticket) return null;

  const jobHistory = Array.isArray(ticket.job_history) ? [...ticket.job_history].sort((a, b) => (a.created_at || 0) - (b.created_at || 0)) : [];
  const latestJob = jobHistory.at(-1) || ticket.last_job;
  const latestExecutionMetadata = latestJob?.execution_metadata || latestJob?.result?.execution || latestJob?.result?.execution_metadata || {};
  const latestProjectDir = latestJob?.project_dir || "—";
  const latestPromptExcerpt = latestJob?.prompt_excerpt || "";
  const latestPromptLength = latestJob?.prompt_length || 0;
  const latestSuccess = latestJob?.success ?? latestJob?.result?.success;
  const latestExitCode = latestJob?.exit_code ?? latestJob?.result?.exit_code ?? null;
  const latestStdoutLines = latestJob?.stdout_lines ?? latestJob?.result?.stdout_lines ?? 0;
  const latestStderrLines = latestJob?.stderr_lines ?? latestJob?.result?.stderr_lines ?? 0;
  const latestFilesChanged = latestJob?.files_changed || latestJob?.result?.files_changed || [];
  const latestIsActiveJob = latestJob?.status === "queued" || latestJob?.status === "running";
  const latestResultLabel = latestJob
    ? (
      latestSuccess === true
        ? "success"
        : latestSuccess === false
          ? (latestIsActiveJob ? "pending" : "failed")
          : (latestIsActiveJob ? "pending" : "unknown")
    )
    : "—";

  return (
    <div className="rounded-lg border border-gray-200 bg-white p-3">
      <div className="text-xs font-medium text-gray-500 mb-2">Latest execution evidence</div>
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3 text-xs text-gray-600">
        <div>
          <div className="font-medium text-gray-500 uppercase">Context</div>
          <div className="mt-1 font-mono truncate" title={latestProjectDir}>{latestProjectDir}</div>
          <div className="mt-1">{latestJob?.mode || "—"}{latestJob?.model ? ` · ${latestJob.model}` : ""}</div>
          <div className="mt-1">Prompt: {latestPromptLength} chars</div>
        </div>
        <div>
          <div className="font-medium text-gray-500 uppercase">Tool execution result</div>
          <div className={`mt-1 font-medium ${latestResultLabel === "success" ? "text-emerald-600" : latestResultLabel === "failed" ? "text-red-600" : "text-gray-800"}`}>
            {latestResultLabel}
          </div>
          <div className="mt-1">Exit code: {latestExitCode ?? "—"}</div>
          <div className="mt-1">stdout {latestStdoutLines} / stderr {latestStderrLines}</div>
        </div>
        <div>
          <div className="font-medium text-gray-500 uppercase">Files</div>
          <div className="mt-1">{latestFilesChanged.length || 0} changed</div>
          {latestFilesChanged.length > 0 && (
            <div className="mt-1 max-h-20 overflow-auto font-mono text-[11px] whitespace-pre-wrap">
              {latestFilesChanged.join(", ")}
            </div>
          )}
        </div>
        <div>
          <div className="font-medium text-gray-500 uppercase">Prompt excerpt</div>
          <div className="mt-1 max-h-20 overflow-auto whitespace-pre-wrap font-mono text-[11px] leading-snug text-gray-700">
            {latestPromptExcerpt || "—"}
          </div>
        </div>
      </div>
      {Object.keys(latestExecutionMetadata).length > 0 && (
        <div className="mt-3">
          <div className="text-xs font-medium text-gray-500 mb-1">Execution metadata</div>
          <pre className="max-h-40 overflow-auto rounded bg-gray-50 p-2 text-[11px] leading-snug text-gray-700 whitespace-pre-wrap">
            {JSON.stringify(latestExecutionMetadata, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}

export default TicketExecutionEvidence;
