// SPEC: PJ2026-01060307 控制面模块化 draft-2026-06-25-p0. pipelinerun module for scripts/src/ci.ts.

// Moved mechanically from scripts/src/ci.ts:1560-1667 for #903.

import { randomUUID } from "node:crypto";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, posix as posixPath } from "node:path";
import { blockedCatalogArtifactIds, catalogSummary, findCiCatalogArtifact, loadCiCatalog, supportedSourceBuildArtifactIds, type CiCatalogArtifact, type CiSourceBuildCatalogArtifact, type CiUpstreamImageCatalogArtifact } from "../ci-catalog";
import { runCommand } from "../command";
import { type UniDeskConfig, repoRoot, rootPath } from "../config";
import { ensureGithubSshIdentityForProvider, gitSshHttpConnectProxySource } from "../deploy-ssh-identity";
import { jobWithTail, listJobs, readJob, startJob } from "../jobs";
import { coreInternalFetch } from "../microservices";
import {
  artifactRegistryReadonlyResultFromCommand,
  buildArtifactRegistryReadonlyProbe,
  parseArtifactRegistryOptions,
  type ArtifactRegistryReadonlyProbe,
} from "../artifact-registry";
import { d601K3sGuardShellLines, d601NativeKubeconfig } from "../d601-k3s-guard";
import { runSshCommandCapture } from "../ssh";

import type { CiOptions, CiPublishBackendCoreOptions, CiPublishUserServiceArtifactOptions } from "./types";

export function pipelineRunManifest(options: CiOptions): string {
  const safeSuffix = new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14).toLowerCase();
  return `apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
  generateName: unidesk-ci-${safeSuffix}-
  namespace: unidesk-ci
  labels:
    app.kubernetes.io/name: unidesk-ci
    app.kubernetes.io/part-of: unidesk
    unidesk.ai/revision: ${JSON.stringify(options.revision)}
spec:
  pipelineRef:
    name: unidesk-ci
  taskRunTemplate:
    serviceAccountName: unidesk-ci-runner
  params:
    - name: repo-url
      value: ${JSON.stringify(options.repoUrl)}
    - name: revision
      value: ${JSON.stringify(options.revision)}
  workspaces:
    - name: shared-workspace
      persistentVolumeClaim:
        claimName: unidesk-ci-cache
`;
}

export function backendCoreArtifactPipelineRunManifest(options: CiPublishBackendCoreOptions): string {
  const safeSuffix = new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14).toLowerCase();
  return `apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
  generateName: backend-core-artifact-${safeSuffix}-
  namespace: unidesk-ci
  labels:
    app.kubernetes.io/name: unidesk-backend-core-artifact-publish
    app.kubernetes.io/part-of: unidesk
    unidesk.ai/service-id: backend-core
    unidesk.ai/revision: ${JSON.stringify(options.commit)}
spec:
  pipelineRef:
    name: unidesk-backend-core-artifact-publish
  taskRunTemplate:
    serviceAccountName: unidesk-ci-runner
  params:
    - name: repo-url
      value: ${JSON.stringify(options.repoUrl)}
    - name: revision
      value: ${JSON.stringify(options.commit)}
    - name: dockerfile
      value: ${JSON.stringify(options.dockerfile)}
    - name: image-repository
      value: ${JSON.stringify(options.imageRepository)}
    - name: source-host-path
      value: ${JSON.stringify(options.sourceHostPath)}
  workspaces:
    - name: shared-workspace
      persistentVolumeClaim:
        claimName: unidesk-ci-cache
`;
}

export function userServiceArtifactPipelineRunManifest(options: CiPublishUserServiceArtifactOptions): string {
  const safeSuffix = new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14).toLowerCase();
  return `apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
  generateName: user-service-artifact-${options.serviceId}-${safeSuffix}-
  namespace: unidesk-ci
  labels:
    app.kubernetes.io/name: unidesk-user-service-artifact-publish
    app.kubernetes.io/part-of: unidesk
    unidesk.ai/service-id: ${JSON.stringify(options.serviceId)}
    unidesk.ai/revision: ${JSON.stringify(options.commit)}
spec:
  pipelineRef:
    name: unidesk-user-service-artifact-publish
  taskRunTemplate:
    serviceAccountName: unidesk-ci-runner
  params:
    - name: repo-url
      value: ${JSON.stringify(options.repoUrl)}
    - name: revision
      value: ${JSON.stringify(options.commit)}
    - name: service-id
      value: ${JSON.stringify(options.serviceId)}
    - name: dockerfile
      value: ${JSON.stringify(options.dockerfile)}
    - name: image-repository
      value: ${JSON.stringify(options.imageRepository)}
    - name: source-host-path
      value: ${JSON.stringify(options.sourceHostPath)}
  workspaces:
    - name: shared-workspace
      persistentVolumeClaim:
        claimName: unidesk-ci-cache
`;
}

export function backendCoreArtifactSourceHostPath(commit: string): string {
  return `/home/ubuntu/.unidesk/ci/backend-core-artifacts/${commit}`;
}

export function userServiceArtifactSourceHostPath(serviceId: string, commit: string): string {
  return `/home/ubuntu/.unidesk/ci/user-service-artifacts/${serviceId}/${commit}`;
}
