export type Row = Record<string, any>;

export type StepStatus = "pending" | "running" | "completed" | "failed" | "retrying" | "skipped" | "cancelled";

export type RunStage = {
  key: string;
  name: string;
  status?: StepStatus;
  step_progress?: number;
  run_progress?: number;
  attempt?: number;
  elapsed_ms?: number;
};

export type StepSnapshot = {
  step_key: string;
  step_name?: string;
  status: StepStatus;
  event_type?: string;
  run_progress?: number;
  step_progress?: number;
  attempt?: number;
  title?: string;
  message?: string;
  entity_type?: string;
  entity_id?: string;
  metrics?: Row;
  visual_payload?: Row;
  updated_at?: string;
};

export type RunEvent = StepSnapshot & {
  event_id: string;
  sequence: number;
  created_at: string;
  progress?: number;
};

export type RunSnapshot = {
  run_id: string;
  status: string;
  current_step: string;
  progress: number;
  task_id?: string;
  summary?: Row;
  started_at?: string;
  completed_at?: string;
  error_message?: string;
  last_sequence?: number;
  steps?: RunStage[];
  step_snapshots?: Record<string, StepSnapshot>;
  entity_index?: Row;
  events?: RunEvent[];
};

export const RUN_STAGES: RunStage[] = [
  { key: "run.initializing", name: "运行初始化" },
  { key: "task.created", name: "巡检任务创建" },
  { key: "uav.dispatching", name: "航线任务下发" },
  { key: "resource.ingesting", name: "多源数据接入" },
  { key: "preprocess.running", name: "数据预处理" },
  { key: "ai.inferencing", name: "AI推理分析" },
  { key: "rule.evaluating", name: "GIS规则判定" },
  { key: "alarm.generating", name: "告警生成" },
  { key: "workorder.dispatching", name: "工单派发" },
  { key: "workorder.closing", name: "工单闭环" },
  { key: "sample.feedback", name: "样本回流" },
  { key: "run.completed", name: "完成汇总" }
];

export function safeObject(value: unknown): Row {
  if (!value) return {};
  if (typeof value === "object") return value as Row;
  try {
    return JSON.parse(String(value));
  } catch {
    return {};
  }
}

export function deepMerge(base: Row, patch: Row): Row {
  const result = { ...base };
  Object.entries(patch).forEach(([key, value]) => {
    const current = result[key];
    if (isPlainObject(current) && isPlainObject(value)) {
      result[key] = deepMerge(current, value as Row);
    } else {
      result[key] = value;
    }
  });
  return result;
}

export function formatTime(value: unknown) {
  if (!value) return "--:--:--";
  const date = new Date(String(value));
  return Number.isNaN(date.getTime()) ? String(value) : date.toLocaleTimeString("zh-CN", { hour12: false });
}

export function formatDuration(value: unknown) {
  const milliseconds = Number(value ?? 0);
  if (milliseconds < 1000) return `${milliseconds}ms`;
  return `${(milliseconds / 1000).toFixed(1)}s`;
}

export function formatValue(value: unknown): string {
  if (Array.isArray(value)) return `${value.length} 项`;
  if (isPlainObject(value)) return Object.entries(value as Row).map(([key, item]) => `${key}: ${item}`).join("，");
  if (typeof value === "boolean") return value ? "是" : "否";
  return String(value ?? "-");
}

export function statusLabel(value: unknown) {
  const labels: Record<string, string> = {
    pending: "未开始",
    created: "已创建",
    checking: "检查中",
    ready: "就绪",
    validating: "校验中",
    dispatching: "下发中",
    flying: "飞行中",
    ingesting: "接入中",
    qualified: "合格",
    running: "执行中",
    completed: "已完成",
    failed: "失败",
    retrying: "重试中",
    skipped: "已跳过",
    cancelled: "已取消",
    closed: "已闭环",
    processing: "处理中",
    delivered: "已送达",
    queued: "待标注",
    excluded: "已排除",
    passed: "已通过",
    suppressed: "已抑制",
    detected: "已识别",
    confirmed: "已确认",
    data_uploading: "数据上传中",
    degraded: "降级运行",
    dispatched: "已派发",
    accepted: "已受理",
    en_route: "赶赴现场",
    on_site: "已到场",
    submitted: "待复核",
    reviewing: "复核中",
    returned: "已退回",
    reinspection_required: "待复检",
    available: "可用",
    blocked: "受阻",
    partial: "部分完成",
    verified: "已核验"
  };
  return labels[String(value)] ?? String(value ?? "-");
}

export function statusTag(value: unknown): "success" | "warning" | "info" | "danger" | "primary" {
  const status = String(value);
  if (["completed", "closed", "ready", "qualified", "passed", "delivered", "available", "verified"].includes(status)) return "success";
  if (["failed", "critical", "blocked", "returned"].includes(status)) return "danger";
  if (["retrying", "cancelled", "pending", "created", "high", "partial", "reinspection_required"].includes(status)) return "warning";
  if (["running", "flying", "dispatching", "ingesting", "processing", "dispatched", "accepted", "en_route", "on_site", "submitted", "reviewing"].includes(status)) return "primary";
  return "info";
}

export function severityLabel(value: unknown) {
  const labels: Record<string, string> = { critical: "严重", high: "高", medium: "中", low: "低" };
  return labels[String(value)] ?? String(value ?? "-");
}

function isPlainObject(value: unknown): value is Row {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
