import { describe, expect, it } from "vitest";
import { query } from "./clickhouse.js";
import { NeedMoreData, Cursor } from "../src/readers/core.js";
import { readDynamic } from "../src/readers/dynamic.js";

// Dynamic needs the experimental flag; some inner casts add their own settings.
async function reader(expr: string, extra = ""): Promise<Cursor> {
  return new Cursor(
    await query(
      `SELECT CAST(${expr} AS Dynamic) SETTINGS allow_experimental_dynamic_type = 1${extra} FORMAT RowBinary`,
    ),
  );
}

describe("readDynamic", () => {
  it("decodes scalars by their inline type tag", async () => {
    expect(readDynamic(await reader("toUInt64(42)"))).toBe(42n); // tag 0x04
    expect(readDynamic(await reader("toInt8(-5)"))).toBe(-5); // tag 0x07
    expect(readDynamic(await reader("toInt32(-1)"))).toBe(-1); // tag 0x09
    expect(readDynamic(await reader("toFloat32(1.5)"))).toBe(1.5); // tag 0x0d
    expect(readDynamic(await reader("toFloat64(1.5)"))).toBe(1.5); // tag 0x0e
    expect(readDynamic(await reader("'hi'"))).toBe("hi"); // tag 0x15
    expect(readDynamic(await reader("true"))).toBe(true); // tag 0x2d
  });

  it("decodes NULL as the Nothing tag (0x00)", async () => {
    const r = await reader("NULL");
    expect(readDynamic(r)).toBeNull();
    expect(r.pos).toBe(1); // lone tag byte, no value
  });

  it("strips the Nullable wrapper: a non-null Nullable(UInt8) is stored as UInt8", async () => {
    const r = await reader("CAST(7 AS Nullable(UInt8))");
    expect(readDynamic(r)).toBe(7); // tag 0x01 (UInt8), not a Nullable wrapper
    expect(r.pos).toBe(2); // tag + 1 value byte
  });

  it("strips the Variant wrapper: stores the active alternative's concrete type", async () => {
    const r = await reader(
      "CAST(42 AS Variant(UInt8, String))",
      ", allow_experimental_variant_type = 1",
    );
    expect(readDynamic(r)).toBe(42); // stored as UInt8 (tag 0x01), no Variant tag
  });

  it("decodes a parameterized FixedString(N) (tag 0x16)", async () => {
    const r = await reader("CAST('ab' AS FixedString(3))");
    expect(readDynamic(r)).toBe("ab "); // N from the header, trailing NUL kept
  });

  it("decodes a Decimal64 carrying its scale in the header (tag 0x1a)", async () => {
    const r = await reader("toDecimal64(1.5, 2)");
    expect(readDynamic(r)).toEqual([150n, 2]); // [unscaled, scale] — scale from header
  });

  it("decodes Date / DateTime / DateTime64 incl. timezone'd variants", async () => {
    expect(readDynamic(await reader("toDate('2024-01-01')"))).toEqual(
      new Date("2024-01-01T00:00:00.000Z"),
    ); // tag 0x0f
    expect(
      readDynamic(await reader("toDateTime('2024-01-01 00:00:00', 'UTC')")),
    ).toEqual(new Date("2024-01-01T00:00:00.000Z")); // tag 0x12, tz consumed
    expect(
      readDynamic(
        await reader("toDateTime64('2024-01-01 00:00:00.5', 3, 'UTC')"),
      ),
    ).toEqual([new Date("2024-01-01T00:00:00.000Z"), 500000000]); // tag 0x14, P+tz
  });

  it("decodes an Enum (tag 0x17) to its name", async () => {
    const r = await reader("CAST('b' AS Enum8('a' = 1, 'b' = 2))");
    // The name<->value pairs in the type header build the lookup, so the
    // underlying Int8 (2) resolves to its name.
    expect(readDynamic(r)).toBe("b");
  });

  it("recurses into Array(UInt8) (tag 0x1e)", async () => {
    const r = await reader("CAST([1, 2, 3] AS Array(UInt8))");
    expect(readDynamic(r)).toEqual([1, 2, 3]);
  });

  it("recurses into nested Array(Array(UInt8))", async () => {
    const r = await reader("CAST([[1], [2, 3]] AS Array(Array(UInt8)))");
    expect(readDynamic(r)).toEqual([[1], [2, 3]]);
  });

  it("recurses into an unnamed Tuple(UInt8, String) (tag 0x1f)", async () => {
    const r = await reader("CAST((1, 'x') AS Tuple(UInt8, String))");
    expect(readDynamic(r)).toEqual([1, "x"]);
  });

  it("recurses into a named Tuple (tag 0x20)", async () => {
    const r = await reader("CAST((1, 'x') AS Tuple(a UInt8, b String))");
    expect(readDynamic(r)).toEqual({ a: 1, b: "x" });
  });

  it("recurses into Map(String, UInt8) (tag 0x27)", async () => {
    const r = await reader("CAST(map('a', 1, 'b', 2) AS Map(String, UInt8))");
    expect(readDynamic(r)).toEqual(
      new Map([
        ["a", 1],
        ["b", 2],
      ]),
    );
  });

  it("sees through LowCardinality(String) (tag 0x26 wraps the inner String)", async () => {
    const r = await reader(
      "CAST('x' AS LowCardinality(String))",
      ", allow_suspicious_low_cardinality_types = 1",
    );
    expect(readDynamic(r)).toBe("x");
  });

  it("recurses into Array(Nullable(UInt8)) — nested Nullable is NOT erased (tag 0x23)", async () => {
    // Top-level Dynamic erases Nullable, but an array with holes genuinely has
    // element type Nullable(UInt8), so the 0x23 tag appears nested.
    const r = await reader("CAST([1, NULL, 3] AS Array(Nullable(UInt8)))");
    expect(readDynamic(r)).toEqual([1, null, 3]);
  });

  it("recurses into Array(Tuple(UInt8, String))", async () => {
    const r = await reader(
      "CAST([(1, 'a'), (2, 'b')] AS Array(Tuple(UInt8, String)))",
    );
    expect(readDynamic(r)).toEqual([
      [1, "a"],
      [2, "b"],
    ]);
  });

  it("recurses into Map(String, Array(UInt8))", async () => {
    const r = await reader(
      "CAST(map('x', [1, 2], 'y', [3]) AS Map(String, Array(UInt8)))",
    );
    expect(readDynamic(r)).toEqual(
      new Map([
        ["x", [1, 2]],
        ["y", [3]],
      ]),
    );
  });

  it("recurses into Array(Map(String, UInt8))", async () => {
    const r = await reader(
      "CAST([map('a', 1), map('b', 2)] AS Array(Map(String, UInt8)))",
    );
    expect(readDynamic(r)).toEqual([new Map([["a", 1]]), new Map([["b", 2]])]);
  });

  it("recurses into Tuple(Array(UInt8), Map(String, UInt8)) — mixed composites", async () => {
    const r = await reader(
      "CAST(([1, 2], map('a', 1)) AS Tuple(Array(UInt8), Map(String, UInt8)))",
    );
    expect(readDynamic(r)).toEqual([[1, 2], new Map([["a", 1]])]);
  });

  it("recurses into a named Tuple of composites with a nested Nullable", async () => {
    const r = await reader(
      "CAST(([1, NULL], (2, 'x')) AS Tuple(xs Array(Nullable(UInt8)), pair Tuple(n UInt8, s String)))",
    );
    // pair is a NAMED tuple, so it decodes to an object, not an array.
    expect(readDynamic(r)).toEqual({ xs: [1, null], pair: { n: 2, s: "x" } });
  });

  it("recurses three levels deep: Array(Map(String, Array(Nullable(UInt8))))", async () => {
    const r = await reader(
      "CAST([map('a', [1, NULL])] AS Array(Map(String, Array(Nullable(UInt8)))))",
    );
    expect(readDynamic(r)).toEqual([new Map([["a", [1, null]]])]);
  });

  it("decodes an Interval, pairing the Int64 count with its unit (tag 0x22)", async () => {
    // The unit kind byte is in the header, so the value carries [count, unit].
    expect(readDynamic(await reader("toIntervalSecond(5)"))).toEqual([
      5n,
      "Second",
    ]);
    expect(readDynamic(await reader("toIntervalSecond(-3)"))).toEqual([
      -3n,
      "Second",
    ]);
  });

  it("maps every Interval unit kind byte to its name", async () => {
    const cases: Array<[string, string]> = [
      ["toIntervalNanosecond(1)", "Nanosecond"],
      ["toIntervalMicrosecond(1)", "Microsecond"],
      ["toIntervalMillisecond(1)", "Millisecond"],
      ["toIntervalSecond(1)", "Second"],
      ["toIntervalMinute(1)", "Minute"],
      ["toIntervalHour(1)", "Hour"],
      ["toIntervalDay(1)", "Day"],
      ["toIntervalWeek(1)", "Week"],
      ["toIntervalMonth(1)", "Month"],
      ["toIntervalQuarter(1)", "Quarter"],
      ["toIntervalYear(1)", "Year"],
    ];
    for (const [expr, unit] of cases) {
      expect(readDynamic(await reader(expr))).toEqual([1n, unit]);
    }
  });

  it("recurses: Array(Interval) carries the unit per value", async () => {
    const r = await reader(
      "CAST([toIntervalDay(1), toIntervalDay(2)] AS Array(IntervalDay))",
    );
    expect(readDynamic(r)).toEqual([
      [1n, "Day"],
      [2n, "Day"],
    ]);
  });

  it("recurses into Array(Variant(...)): discriminant indexes the sorted alternatives (tag 0x2a)", async () => {
    // Variant(UInt8, String) sorts to [String(0), UInt8(1)]; the header lists
    // alternatives in that sorted order, which the per-value discriminant
    // indexes (0xff = NULL).
    const r = await reader(
      "CAST([42::Variant(UInt8, String), 'hi'::Variant(UInt8, String), NULL::Variant(UInt8, String)] AS Array(Variant(UInt8, String)))",
      ", allow_experimental_variant_type = 1, allow_suspicious_variant_types = 1",
    );
    expect(readDynamic(r)).toEqual([42, "hi", null]);
  });

  it("Variant alternatives are sorted by type name regardless of declaration order", async () => {
    // Declared (String, UInt8) but still sorts to [String(0), UInt8(1)].
    const r = await reader(
      "CAST([7::Variant(Int32, Float64)] AS Array(Variant(Int32, Float64)))",
      ", allow_experimental_variant_type = 1, allow_suspicious_variant_types = 1",
    );
    expect(readDynamic(r)).toEqual([7]); // Int32 alternative, discriminant 1
  });

  it("recurses through a nested Dynamic: Map(String, Dynamic) with mixed value types (tag 0x2b)", async () => {
    // The Map value type is Dynamic, so each value is self-describing: 'a' is an
    // Int32, 'b' is a String. The 0x2b header (max_dynamic_types) is consumed,
    // then each value is a recursive readDynamic.
    const r = await reader(
      "CAST(map('a', toInt32(7)::Dynamic, 'b', 'hi'::Dynamic) AS Map(String, Dynamic))",
    );
    expect(readDynamic(r)).toEqual(
      new Map<string, unknown>([
        ["a", 7],
        ["b", "hi"],
      ]),
    );
  });

  it("recurses through Array(Dynamic) nested in a Dynamic", async () => {
    const r = await reader(
      "CAST(['x'::Dynamic, 'y'::Dynamic] AS Array(Dynamic))",
    );
    expect(readDynamic(r)).toEqual(["x", "y"]);
  });

  it("decodes a composite value through a nested Dynamic (Array + String)", async () => {
    const r = await reader(
      "CAST(map('nums', [1, 2, 3]::Array(UInt8)::Dynamic, 's', 'hi'::Dynamic) AS Map(String, Dynamic))",
    );
    expect(readDynamic(r)).toEqual(
      new Map<string, unknown>([
        ["nums", [1, 2, 3]],
        ["s", "hi"],
      ]),
    );
  });

  it("the nested-Dynamic max_dynamic_types header byte does not affect decoding", async () => {
    // Same value, but the inner Dynamic declares max_types=1 (header byte 0x01
    // instead of the default 0x20). The value wire is identical; we skip the byte.
    const r = await reader("map('a', toInt32(7)::Dynamic(max_types=1))");
    expect(readDynamic(r)).toEqual(new Map([["a", 7]]));
  });

  it("overflow values still use the standard tag+value encoding (shared variant is storage-only)", async () => {
    // A Dynamic(max_types=1) column holding three distinct types: only one fits
    // the single type slot, the others overflow to ClickHouse's "shared data".
    // That split is a Native-format/storage concern — in RowBinary EVERY value
    // is normalized back to a plain (type tag, value), so reading is uniform.
    const r = new Cursor(
      await query(
        "SELECT c FROM values('c Dynamic(max_types=1)', (toInt32(7)), ('hi'), (toFloat64(1.5))) SETTINGS allow_experimental_dynamic_type = 1 FORMAT RowBinary",
      ),
    );
    expect(readDynamic(r)).toBe(7); // Int8 tag (values() narrowed the literal)
    expect(readDynamic(r)).toBe("hi"); // String tag
    expect(readDynamic(r)).toBe(1.5); // Float64 tag
  });

  it("decodes a Nested as Array(Tuple(...)) — array of row objects (tag 0x2f)", async () => {
    // Nested(a UInt8, b String) is Array(Tuple(a UInt8, b String)) on the wire;
    // its header matches a named Tuple's, so it decodes to an array of {a, b}.
    const r = await reader(
      "CAST([(1, 'x'), (2, 'y')]::Nested(a UInt8, b String) AS Dynamic)",
    );
    expect(readDynamic(r)).toEqual([
      { a: 1, b: "x" },
      { a: 2, b: "y" },
    ]);
  });

  it("throws on a tag outside the encoding table (0xfe), reporting the hex", () => {
    const r = new Cursor(Buffer.from([0xfe]));
    expect(() => readDynamic(r)).toThrow(/unknown Dynamic type tag 0xfe/);
  });

  describe("advance() edge cases", () => {
    it("throws NeedMoreData for every incomplete prefix (0 .. full.length-1)", async () => {
      const full = await query(
        "SELECT CAST(toUInt64(42) AS Dynamic) SETTINGS allow_experimental_dynamic_type = 1 FORMAT RowBinary",
      );
      for (let len = 0; len < full.length; len++) {
        const r = new Cursor(full.subarray(0, len));
        let thrown: unknown;
        try {
          readDynamic(r);
        } catch (e) {
          thrown = e;
        }
        expect(thrown, `prefix length ${len} of ${full.length}`).toBe(
          NeedMoreData,
        );
      }
    });
  });
});
