// src/lib/log-transport-console.ts
// Copyright (C) 2026 Rob Colbert <rob.colbert@openplatform.us>
// Licensed under the Apache License, Version 2.0

import * as util from "node:util";

import dayjs from "dayjs";
import color from "ansicolor";

import { GadgetLogLevel } from "./log.ts";
import { GadgetLogTransport } from "./log-transport.ts";
import { GadgetComponent } from "./component.ts";

export class GadgetLogTransportConsole implements GadgetLogTransport {
  async writeLog(
    timestamp: Date,
    component: GadgetComponent,
    level: GadgetLogLevel,
    message: string,
    metadata?: unknown,
  ): Promise<void> {
    let clevel = level.padEnd(5);
    switch (level) {
      case "debug":
        clevel = color.darkGray(clevel);
        break;
      case "info":
        clevel = color.green(clevel);
        break;
      case "warn":
        clevel = color.yellow(clevel);
        break;
      case "alert":
        clevel = color.red(clevel);
        break;
      case "error":
        clevel = color.bgRed.white(clevel);
        break;
      case "crit":
        clevel = color.bgRed.yellow(clevel);
        break;
      case "fatal":
        clevel = color.bgRed.darkGray(clevel);
        break;
    }

    const ccomponent = color.cyan(component.name);
    const ctimestamp = color.darkGray(
      dayjs(timestamp).format("YYYY-MM-DD HH:mm:ss.SSS"),
    );
    const cmessage = color.darkGray(message);

    if (metadata) {
      console.log(
        `${ctimestamp} ${clevel} ${ccomponent} ${cmessage}`,
        util.inspect(metadata, false, Infinity, true),
      );
    } else {
      console.log(`${ctimestamp} ${clevel} ${ccomponent} ${cmessage}`);
    }
  }
}
