import { Args, Command } from "@oclif/core";
import { sharedFlags } from "../command-helpers.mjs";
import { collectArtifactEntries, loadCurrentRunArtifact } from "../viewer.mjs";

export default class ArtifactsCommand extends Command {
  static summary = "List persisted artifacts from the latest run";

  static enableJsonFlag = true;

  static args = {
    file: Args.string({
      description: "Optional file path to filter artifacts",
      required: false,
    }),
  };

  static flags = sharedFlags;

  async run() {
    const { args, flags } = await this.parse(ArtifactsCommand);
    const productDir = flags.dir || process.cwd();
    const runArtifact = loadCurrentRunArtifact(productDir);
    const entries = collectArtifactEntries(productDir, runArtifact, args.file || null, flags.service || null)
      .map((entry) => ({
        service: entry.service.name,
        suite: `${entry.suite.type}:${entry.suite.name}`,
        file: entry.file.path,
        name: entry.artifactRef.name,
        kind: entry.artifactRef.kind,
        summary: entry.artifactRef.summary,
        path: entry.artifactRef.path,
      }));

    if (!this.jsonEnabled()) {
      for (const entry of entries) {
        this.log(`${entry.file}`);
        this.log(`  ${entry.name}${entry.kind ? ` [${entry.kind}]` : ""}`);
        if (entry.summary) this.log(`    ${entry.summary}`);
        this.log(`    ${entry.path}`);
      }
    }

    return entries;
  }
}
