import { describe, test, expect } from "vitest"

function parseArgs(argv: string[]): Record<string, string> {
  const out: Record<string, string> = {}
  for (let i = 0; i < argv.length; i++) {
    const a = argv[i]
    if (a.startsWith("--")) {
      const key = a.slice(2)
      const val = argv[i + 1] ?? ""
      out[key] = val
      i++
    }
  }
  return out
}

function parseSlotsArg(slotsStr: string | undefined): Record<string, string> {
  const slots: Record<string, string> = {}
  if (slotsStr) {
    for (const pair of slotsStr.split(",")) {
      const eq = pair.indexOf("=")
      if (eq !== -1) slots[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim()
    }
  }
  return slots
}

describe("cli — arg parsing", () => {
  test("parses title and out", () => {
    const opts = parseArgs(["--title", "Hello", "--out", "/tmp/x.png"])
    expect(opts.title).toBe("Hello")
    expect(opts.out).toBe("/tmp/x.png")
  })

  test("default out is ./assets/cover.png", () => {
    const opts = parseArgs(["--title", "Test"])
    const out = opts.out ?? "./assets/cover.png"
    expect(out).toBe("./assets/cover.png")
  })

  test("parses slots string into object", () => {
    const slots = parseSlotsArg("icon=mic,sub-icon=opencode,badge=./x.svg")
    expect(slots.icon).toBe("mic")
    expect(slots["sub-icon"]).toBe("opencode")
    expect(slots.badge).toBe("./x.svg")
  })

  test("empty slots string yields empty object", () => {
    expect(parseSlotsArg(undefined)).toEqual({})
    expect(parseSlotsArg("")).toEqual({})
  })

  test("subtitle is optional", () => {
    const opts = parseArgs(["--title", "Test"])
    expect(opts.subtitle).toBeUndefined()
  })
})