// ═══════════════════════════════════════════════════════════
// GooseFactory Shared Types — from CONTRACTS.md
// ═══════════════════════════════════════════════════════════

// --- Enums & Literals ---

export type PipelineStatus = "active" | "paused" | "completed" | "failed" | "archived";
export type Priority = "critical" | "high" | "medium" | "low";
export type PipelineTemplate = "mcp-server-standard" | "mcp-server-minimal" | "mcp-server-enterprise";

export type PipelineStage =
  | "intake"
  | "scaffolding"
  | "building"
  | "testing"
  | "review"
  | "staging"
  | "production"
  | "published";

export type TaskType = "approval" | "review" | "decision" | "manual_action" | "fix_required";
export type TaskStatus = "pending" | "claimed" | "in_progress" | "completed" | "expired" | "escalated";
export type TaskDecision = "approved" | "rejected" | "deferred" | "escalated";

export type ApprovalType = "stage_gate" | "deploy" | "code_review" | "manual_check";
export type ApprovalStatus = "pending" | "approved" | "rejected" | "expired";

export type AgentType = "ai_builder" | "test_runner" | "deployer" | "monitor";
export type AgentStatus = "idle" | "active" | "error" | "offline";

export type AssetType = "code" | "config" | "docs" | "build" | "test_report" | "screenshot";
export type StageStatus = "pending" | "active" | "completed" | "skipped" | "failed";

// --- Core Entities ---

export interface Pipeline {
  id: string;
  name: string;
  slug: string;
  template: PipelineTemplate;
  platform: string;
  currentStage: PipelineStage;
  status: PipelineStatus;
  priority: Priority;
  createdBy: string;
  assigneeId: string | null;
  config: Record<string, unknown>;
  metadata: Record<string, unknown>;
  slaDeadline: string | null;
  startedAt: string;
  completedAt: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface PipelineStageRecord {
  id: string;
  pipelineId: string;
  stageName: PipelineStage;
  stageOrder: number;
  status: StageStatus;
  requiresApproval: boolean;
  approvalType: "manual" | "auto" | "conditional";
  autoAdvance: boolean;
  validationRules: ValidationRule[];
  enteredAt: string | null;
  completedAt: string | null;
  durationSeconds: number | null;
  createdAt: string;
}

export interface ValidationRule {
  type: "test_coverage" | "tests_passing" | "required_asset" | "approval_count" | "custom";
  config: Record<string, unknown>;
}

export interface Task {
  id: string;
  pipelineId: string | null;
  stageName: PipelineStage | null;
  type: TaskType;
  title: string;
  description: string | null;
  context: TaskContext;
  status: TaskStatus;
  priority: Priority;
  assigneeId: string | null;
  claimedAt: string | null;
  claimedBy: string | null;
  decision: TaskDecision | null;
  decisionNotes: string | null;
  decisionData: Record<string, unknown>;
  decidedAt: string | null;
  decidedBy: string | null;
  slaDeadline: string | null;
  slaWarningsSent: number;
  slaBreached: boolean;
  escalationLevel: number;
  blocksStageAdvance: boolean;
  blocksPipelineId: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface TaskContext {
  summary: string;
  details?: string;
  testResults?: TestResults;
  diffSummary?: DiffSummary;
  metrics?: Record<string, number>;
  relatedAssets?: string[];
  modalType?: string;
  modalConfig?: Record<string, unknown>;
}

export interface TestResults {
  total: number;
  passed: number;
  failed: number;
  skipped: number;
  coveragePercent: number;
  failureDetails?: TestFailure[];
}

export interface TestFailure {
  testName: string;
  error: string;
  file?: string;
  line?: number;
}

export interface DiffSummary {
  filesChanged: number;
  insertions: number;
  deletions: number;
  files: DiffFile[];
}

export interface DiffFile {
  path: string;
  status: "added" | "modified" | "deleted" | "renamed";
  insertions: number;
  deletions: number;
  patch?: string;
}

export interface Approval {
  id: string;
  taskId: string;
  pipelineId: string;
  stageName: PipelineStage;
  type: ApprovalType;
  status: ApprovalStatus;
  approvedBy: string | null;
  approvedAt: string | null;
  rejectionReason: string | null;
  conditions: string[];
  requiredApprovers: number;
  currentApprovers: number;
  createdAt: string;
}

export interface Agent {
  id: string;
  name: string;
  type: AgentType;
  status: AgentStatus;
  currentTaskId: string | null;
  currentPipelineId: string | null;
  health: AgentHealth;
  capabilities: string[];
  config: Record<string, unknown>;
  tasksCompletedTotal: number;
  avgTaskDurationSeconds: number | null;
  createdAt: string;
  updatedAt: string;
}

export interface AgentHealth {
  uptimeSeconds: number;
  tasksCompleted24h: number;
  errorRate: number;
  lastHeartbeat: string;
}

export interface Asset {
  id: string;
  pipelineId: string;
  stageName: PipelineStage | null;
  type: AssetType;
  name: string;
  path: string | null;
  storageKey: string;
  storageBucket: string | null;
  sizeBytes: number;
  contentType: string;
  checksumSha256: string;
  version: number;
  previousVersionId: string | null;
  generatedBy: string;
  generatorType: "user" | "agent" | "ci";
  metadata: Record<string, unknown>;
  createdAt: string;
}

export interface AuditEntry {
  id: string;
  actorType: "user" | "agent" | "system" | "webhook";
  actorId: string | null;
  actorName: string | null;
  action: string;
  entityType: string;
  entityId: string;
  changes: Record<string, { from: unknown; to: unknown }>;
  metadata: Record<string, unknown>;
  createdAt: string;
}

export interface TaskStats {
  pending: number;
  inProgress: number;
  blocked: number;
  avgWaitTimeMinutes: number;
  slaBreaches: number;
  byPriority: Record<Priority, number>;
  byType: Record<TaskType, number>;
}

export interface DashboardSummary {
  pipelines: {
    active: number;
    paused: number;
    completed: number;
    failed: number;
  };
  tasks: TaskStats;
  agents: {
    total: number;
    active: number;
    idle: number;
    error: number;
    offline: number;
  };
  recentActivity: AuditEntry[];
  slaStatus: {
    onTrack: number;
    warning: number;
    breached: number;
  };
}

export interface PipelineTemplateConfig {
  id: PipelineTemplate;
  name: string;
  description: string;
  stages: PipelineStage[];
  defaultConfig: Record<string, unknown>;
  requiredAssets: AssetType[];
  validationRules: ValidationRule[];
}

export interface PipelineDetailState {
  pipeline: Pipeline;
  stages: PipelineStageRecord[];
  currentTasks: Task[];
  recentAssets: Asset[];
  blockers: BlockerInfo[];
  timeline: AuditEntry[];
}

export interface ServerStatus {
  name: string;
  pipelineId: string;
  stage: PipelineStage;
  health: "healthy" | "degraded" | "failing" | "unknown";
  deployments: {
    staging: DeploymentInfo | null;
    production: DeploymentInfo | null;
  };
  lastTestRun: TestResults | null;
  metrics: Record<string, number>;
}

export interface DeploymentInfo {
  version: string;
  deployedAt: string;
  url: string;
  status: "running" | "stopped" | "failed";
}

export interface BlockerInfo {
  blockerType: "task" | "stage" | "agent" | "dependency";
  entityId: string;
  title: string;
  pipelineId: string;
  pipelineName: string;
  priority: Priority;
  hoursBlocked: number;
  blockReason: string;
  suggestedAction?: string;
}

// --- API Response Wrappers ---

export interface ApiResponse<T> {
  ok: true;
  data: T;
  meta?: {
    requestId: string;
    timestamp: string;
    pagination?: {
      page: number;
      limit: number;
      total: number;
      totalPages: number;
      hasNext: boolean;
      hasPrev: boolean;
    };
  };
}

export interface ApiError {
  ok: false;
  error: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
    field?: string;
    requestId: string;
  };
}
