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

export default class ShowCommand extends Command {
  static summary = "Show the most useful details for one file from the latest run";

  static enableJsonFlag = true;

  static args = {
    file: Args.string({
      description: "File path to inspect; defaults to the first failed file",
      required: false,
    }),
  };

  static flags = {
    ...sharedFlags,
    "log-tail": Flags.integer({
      description: "Number of backend log lines to include",
      default: 12,
    }),
  };

  async run() {
    const { args, flags } = await this.parse(ShowCommand);
    const productDir = flags.dir || process.cwd();
    const runArtifact = loadCurrentRunArtifact(productDir);
    const subject = resolveFileSubject(runArtifact, args.file || null, flags.service || null);
    const result = {
      file: subject.file,
      suite: {
        name: subject.suite.name,
        type: subject.suite.type,
      },
      service: {
        name: subject.service.name,
      },
    };
    if (!this.jsonEnabled()) {
      for (const line of formatFileDetail(productDir, runArtifact, subject, { logTail: flags["log-tail"] })) {
        this.log(line);
      }
    }
    return result;
  }
}
