import { Args, Command, Flags } from "@oclif/core";
import { sharedFlags } from "../command-helpers.mjs";
import { readLogTail } from "../../runner/logs.mjs";
import { getServiceLogRefs, loadCurrentRunArtifact, resolveFileSubject } from "../viewer.mjs";
import path from "path";

export default class LogsCommand extends Command {
  static summary = "Show backend log tails relevant to one file from the latest run";

  static enableJsonFlag = true;

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

  static flags = {
    ...sharedFlags,
    tail: Flags.integer({
      description: "Number of lines to show from each log",
      default: 40,
    }),
  };

  async run() {
    const { args, flags } = await this.parse(LogsCommand);
    const productDir = flags.dir || process.cwd();
    const runArtifact = loadCurrentRunArtifact(productDir);
    const subject = resolveFileSubject(runArtifact, args.file || null, flags.service || null);
    const logs = getServiceLogRefs(runArtifact, subject.service.name).map((entry) => ({
      ...entry,
      lines: readLogTail(path.join(productDir, entry.path), flags.tail),
    }));

    if (!this.jsonEnabled()) {
      for (const entry of logs) {
        this.log(`${entry.runtimeLabel}`);
        this.log(`  ${entry.path}`);
        for (const line of entry.lines) this.log(`  ${line}`);
      }
    }

    return logs;
  }
}
