// Unicode 17.0.0 Default Case Conversion lowercase (und root — byte-identical
// for en, fr, de, es, and every tag without a casing tailoring; only tr/az
// and lt differ and would be separate components).
// Matches golang.org/x/text@v0.40.0 cases.Lower(language.English): full
// mappings from UnicodeData + unconditional SpecialCasing, the Final_Sigma
// context rule for U+03A3 (part of Unicode default lowercase per rule R1;
// Elixir's String.downcase/2 exposes it separately as mode :greek).
// input_utf8_cap makes valid UTF-8 a host precondition.
// Tables generated by tools/casegen.
const tables = @import("lib/unicode-17-lowercase-tables.zig");
const utf8 = @import("lib/utf8.zig");
const std = @import("std");

const INPUT_CAP: usize = 1024 * 1024;
// Worst-case growth is 1.5x (e.g. U+023A 2 bytes -> U+2C65 3 bytes).
const OUTPUT_CAP: usize = INPUT_CAP * 3 / 2;

var input_buf: [INPUT_CAP]u8 = undefined;
var output_buf: [OUTPUT_CAP]u8 = undefined;

export fn input_ptr() u32 {
    return @as(u32, @intCast(@intFromPtr(&input_buf)));
}

export fn input_utf8_cap() u32 {
    return @as(u32, @intCast(INPUT_CAP));
}

export fn output_utf8_cap() u32 {
    return @as(u32, @intCast(OUTPUT_CAP));
}

// ranges is a flat sorted array of inclusive [lo, hi] pairs.
fn inRanges(ranges: []const u32, cp: u32) bool {
    var lo: usize = 0;
    var hi: usize = ranges.len / 2;
    while (lo < hi) {
        const mid = lo + (hi - lo) / 2;
        if (ranges[mid * 2 + 1] < cp) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    return lo < ranges.len / 2 and ranges[lo * 2] <= cp;
}

fn isCased(cp: u32) bool {
    return inRanges(&tables.cased_ranges, cp);
}

fn isCaseIgnorable(cp: u32) bool {
    return inRanges(&tables.case_ignorable_ranges, cp);
}

// Returns the mapped UTF-8 bytes, or null when cp lowercases to itself.
fn lookupLower(cp: u32) ?[]const u8 {
    var lo: usize = 0;
    var hi: usize = tables.map_keys.len;
    while (lo < hi) {
        const mid = lo + (hi - lo) / 2;
        if (tables.map_keys[mid] < cp) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    if (lo >= tables.map_keys.len or tables.map_keys[lo] != cp) return null;
    const packed_val = tables.map_packed[lo];
    const off = packed_val >> 8;
    const len = packed_val & 0xFF;
    return tables.map_blob[off .. off + len];
}

const SIGMA: u32 = 0x03A3;
const SIGMA_FINAL = [_]u8{ 0xCF, 0x82 }; // ς
const SIGMA_SMALL = [_]u8{ 0xCF, 0x83 }; // σ

// Final_Sigma "After" condition: the next non-case-ignorable character, if
// any, must not be cased. The host guarantees valid UTF-8.
fn followedByCased(bytes: []const u8) bool {
    var i: usize = 0;
    while (i < bytes.len) {
        const d = utf8.decode(bytes[i..]);
        if (!d.valid) @trap();
        if (isCaseIgnorable(d.cp)) {
            i += d.size;
            continue;
        }
        return isCased(d.cp);
    }
    return false;
}

fn emit(out: *usize, bytes: []const u8) void {
    if (out.* + bytes.len > OUTPUT_CAP) @trap();
    for (bytes) |b| {
        output_buf[out.*] = b;
        out.* += 1;
    }
}

fn renderImpl(input_size_in: u32) u32 {
    const input_size: usize = @intCast(input_size_in);
    if (input_size > INPUT_CAP) @trap();

    const input = input_buf[0..input_size];
    var out: usize = 0;
    var prev_cased = false;

    var i: usize = 0;
    while (i < input_size) {
        const d = utf8.decode(input[i..]);

        if (!d.valid) @trap();

        if (d.cp == SIGMA) {
            const final = prev_cased and !followedByCased(input[i + d.size ..]);
            emit(&out, if (final) &SIGMA_FINAL else &SIGMA_SMALL);
            prev_cased = true;
            i += d.size;
            continue;
        }

        if (lookupLower(d.cp)) |lower| {
            emit(&out, lower);
        } else {
            emit(&out, input[i .. i + d.size]);
        }

        if (!isCaseIgnorable(d.cp)) {
            prev_cased = isCased(d.cp);
        }
        i += d.size;
    }

    return @as(u32, @intCast(out));
}

export fn render(input_size_in: u32) packed struct(u64) {
    output_size: u32,
    output_ptr: u31,
    failed: u1,
} {
    return .{
        .output_size = renderImpl(input_size_in),
        .output_ptr = @intCast(@intFromPtr(&output_buf)),
        .failed = 0,
    };
}

fn utf8Len(cp: u32) usize {
    if (cp <= 0x7f) return 1;
    if (cp <= 0x7ff) return 2;
    if (cp <= 0xffff) return 3;
    return 4;
}

test "every generated mapping fits the three-to-two byte bound" {
    for (tables.map_keys, tables.map_packed) |cp, packed_value| {
        const mapped_len: usize = @intCast(packed_value & 0xff);
        try std.testing.expect(mapped_len * 2 <= utf8Len(cp) * 3);
    }
}

test "maximum input fits at the worst-case lowercase expansion" {
    var i: usize = 0;
    while (i < INPUT_CAP) : (i += 2) {
        input_buf[i] = 0xc8;
        input_buf[i + 1] = 0xba; // U+023A
    }

    try std.testing.expectEqual(@as(u32, OUTPUT_CAP), renderImpl(INPUT_CAP));
}
