import type { ProjectIssueStatus } from "./project-issue.js";

export const PROJECT_ISSUE_STATUSES = [
  "open",
  "queued",
  "working",
  "needs-input",
  "completed",
  "failed",
] as const;

export const PROJECT_RUN_STATUSES = [
  "ready",
  "queued",
  "working",
  "needs-input",
  "completed",
  "failed",
] as const;

export type ProjectRunStatus = (typeof PROJECT_RUN_STATUSES)[number];

export type ProjectWorkPhase =
  | "captured"
  | "queued"
  | "active"
  | "waiting"
  | "completed"
  | "failed";

export type ProjectVerificationStatus =
  | "not-started"
  | "running"
  | "blocked"
  | "passed"
  | "failed";

export interface ProjectWorkStatus {
  readonly label: string;
  readonly phase: ProjectWorkPhase;
  readonly verification: ProjectVerificationStatus;
}

const NEXT_ACTION_MAP: Readonly<
  Record<ProjectIssueStatus | ProjectRunStatus, string>
> = {
  completed: "Review the pull request",
  failed: "Review the failure and retry",
  "needs-input": "Resolve the open question",
  open: "Start the project manager",
  queued: "Watch the run progress",
  ready: "Watch the run progress",
  working: "Wait for verification",
};

const STATUS_MAP: Readonly<
  Record<ProjectIssueStatus | ProjectRunStatus, ProjectWorkStatus>
> = {
  completed: {
    label: "Completed",
    phase: "completed",
    verification: "passed",
  },
  failed: {
    label: "Failed",
    phase: "failed",
    verification: "failed",
  },
  "needs-input": {
    label: "Needs your input",
    phase: "waiting",
    verification: "blocked",
  },
  open: {
    label: "Ready to start",
    phase: "captured",
    verification: "not-started",
  },
  queued: {
    label: "Queued",
    phase: "queued",
    verification: "not-started",
  },
  ready: {
    label: "Ready",
    phase: "queued",
    verification: "not-started",
  },
  working: {
    label: "In progress",
    phase: "active",
    verification: "running",
  },
};

export const getProjectWorkStatus = (
  status: ProjectIssueStatus | ProjectRunStatus
): ProjectWorkStatus => STATUS_MAP[status];

export const getProjectWorkProgress = (
  status: ProjectIssueStatus | ProjectRunStatus
): number => {
  switch (status) {
    case "completed": {
      return 100;
    }
    case "failed": {
      return 58;
    }
    case "needs-input": {
      return 78;
    }
    case "working": {
      return 68;
    }
    case "queued":
    case "ready": {
      return 24;
    }
    case "open": {
      return 8;
    }
    default: {
      return 0;
    }
  }
};

export const getProjectWorkNextAction = (
  status: ProjectIssueStatus | ProjectRunStatus
): string => NEXT_ACTION_MAP[status];
