#!/usr/bin/env python3
"""Generate exact stateful Classic _far pointer/indexing checkpoints."""

from __future__ import annotations

import argparse


MASK8 = (1 << 8) - 1
MASK16 = (1 << 16) - 1
MASK32 = (1 << 32) - 1
SIGNATURE_SEED = 0x16600141
GROUP_SIGNATURE_SEED = 0xFAD00000
ITERATIONS = 128
CHECKPOINT_INTERVAL = 8
OPERATION_COUNT = 16
SUITE_ID = 313
SEEDS = (0x1660FA41, 0xC1665EED, 0x0123F00D)

BYTE_COUNT = 4032
WORD_COUNT = 2016
LONG_COUNT = 1008
RECORD_COUNT = 504


def u8(value: int) -> int:
    return value & MASK8


def u16(value: int) -> int:
    return value & MASK16


def u32(value: int) -> int:
    return value & MASK32


def s16(value: int) -> int:
    value &= MASK16
    return value - 0x10000 if value & 0x8000 else value


def xorshift16(value: int) -> int:
    value ^= value << 7 & MASK16
    value ^= value >> 9
    value ^= value << 8 & MASK16
    return value & MASK16


def next_u32(state: tuple[int, int]) -> tuple[tuple[int, int], int]:
    low = xorshift16(state[0])
    high = xorshift16(state[1])
    if low == 0 and high == 0:
        high = 1
    return (low, high), (high << 16) | low


def signature_step(signature: int, case_id: int, value: int) -> int:
    case_id &= MASK16
    tag = (case_id << 16) | case_id
    rotated = ((signature << 5) | (signature >> 27)) & MASK32
    return (rotated ^ value ^ tag) & MASK32


def initial_arena(seed: int) -> dict[str, list]:
    seed = u16(seed)
    repeated = (seed << 16) | seed
    byte_values = [
        u8(seed + index * 37 + (index >> 4) * 11)
        for index in range(BYTE_COUNT)
    ]
    word_values = [
        u16(seed ^ index * 257 ^ 0xA55A)
        for index in range(WORD_COUNT)
    ]
    long_values = [
        u32(repeated ^ (index << 8) ^ index ^ 0x13579BDF)
        for index in range(LONG_COUNT)
    ]
    records = []
    for index in range(RECORD_COUNT):
        records.append([
            u8(seed + index * 13 + 0x31),
            u8((seed >> 8) + index * 29 + 0x7B),
            u16(seed ^ index * 193 ^ 0x5AA5),
            u32(repeated + (index << 16) + (index << 9) + index +
                0x2468ACE0),
        ])
    return {
        "bytes": byte_values,
        "words": word_values,
        "longs": long_values,
        "records": records,
    }


def operation_count(operation: int) -> int:
    if operation <= 2 or 12 <= operation <= 13 or operation == 15:
        return BYTE_COUNT
    if operation <= 5 or operation == 14:
        return WORD_COUNT
    if operation <= 8:
        return LONG_COUNT
    return RECORD_COUNT


def operation_indices(iteration: int, operation: int,
                      raw_index: int, raw_other: int) -> tuple[int, int]:
    count = operation_count(operation)
    edge = iteration & 7
    if edge == 0:
        return 0, count - 1
    if edge == 1:
        return count - 1, 0
    if edge == 2:
        return 1, count - 2
    if edge == 3:
        return count - 2, 1
    return (u16(raw_index + operation * 0x1111) % count,
            u16(raw_other ^ operation * 0x0101) % count)


def record_digest(record: list[int]) -> int:
    return u32(record[3] ^ (record[2] << 16) ^
               (record[1] << 8) ^ record[0])


def evaluate(arena: dict[str, list], operation: int, index: int,
             other: int, value: int) -> int:
    bytes_ = arena["bytes"]
    words = arena["words"]
    longs = arena["longs"]
    records = arena["records"]

    if operation == 0:
        return bytes_[index % BYTE_COUNT]
    if operation == 1:
        index %= BYTE_COUNT
        bytes_[index] = u8(value)
        return bytes_[index]
    if operation == 2:
        index %= BYTE_COUNT
        bytes_[index] ^= u8(value >> 8)
        return bytes_[index]
    if operation == 3:
        return words[index % WORD_COUNT]
    if operation == 4:
        index %= WORD_COUNT
        words[index] = u16(value)
        return words[index]
    if operation == 5:
        index %= WORD_COUNT
        words[index] = u16(words[index] + value)
        return words[index]
    if operation == 6:
        return longs[index % LONG_COUNT]
    if operation == 7:
        index %= LONG_COUNT
        longs[index] = u32(value)
        return longs[index]
    if operation == 8:
        index %= LONG_COUNT
        longs[index] = u32(longs[index] ^ value)
        return longs[index]
    if operation == 9:
        return record_digest(records[index % RECORD_COUNT])
    if operation == 10:
        record = records[index % RECORD_COUNT]
        record[0] = u8(record[0] + value)
        record[1] = u8(record[1] ^ (value >> 8))
        record[2] = u16(record[2] + (value >> 16))
        record[3] = u32(record[3] ^ value)
        return record_digest(record)
    if operation == 11:
        index %= RECORD_COUNT
        neighbor = (index + 1) % RECORD_COUNT
        return u32(records[index][3] + records[neighbor][2] +
                   (records[neighbor][0] << 24))
    if operation == 12:
        lhs = index % BYTE_COUNT
        rhs = other % BYTE_COUNT
        difference = s16(lhs - rhs)
        flags = int(lhs == rhs) | (int(lhs < rhs) << 1) | \
            (int(lhs > rhs) << 2)
        return u32((difference & MASK16) << 16 |
                   bytes_[lhs] << 8 | flags)
    if operation == 13:
        index %= BYTE_COUNT
        span = BYTE_COUNT - index
        step = other % span
        return u32(step << 16 | bytes_[index + step])
    if operation == 14:
        lhs = index % WORD_COUNT
        rhs = other % WORD_COUNT
        difference = s16(lhs - rhs)
        return u32((difference & MASK16) << 16 | words[lhs])
    byte_index = index % BYTE_COUNT
    word_index = other % WORD_COUNT
    long_index = index % LONG_COUNT
    record_index = other % RECORD_COUNT
    return u32(longs[long_index] ^ records[record_index][3] ^
               words[word_index] << 16 ^ bytes_[byte_index])


def simulate_seed(seed_index: int, seed: int) -> list[list[int]]:
    arena = initial_arena(seed)
    state = (seed & MASK16, seed >> 16)
    signatures = [
        GROUP_SIGNATURE_SEED ^ ((seed_index + 1) << 8) ^ operation
        for operation in range(OPERATION_COUNT)
    ]
    result = [[] for _ in range(OPERATION_COUNT)]
    for iteration in range(ITERATIONS):
        state, raw0 = next_u32(state)
        state, value = next_u32(state)
        raw_index = raw0 & MASK16
        raw_other = raw0 >> 16
        for operation in range(OPERATION_COUNT):
            index, other = operation_indices(
                iteration, operation, raw_index, raw_other)
            actual = evaluate(arena, operation, index, other, value)
            signatures[operation] = signature_step(
                signatures[operation], iteration + 1, actual)
            if (iteration + 1) % CHECKPOINT_INTERVAL == 0:
                result[operation].append(signatures[operation])
    return result


def matrices() -> list[list[list[int]]]:
    return [simulate_seed(index, seed) for index, seed in enumerate(SEEDS)]


def checkpoints_flat() -> list[int]:
    return [value for seed_matrix in matrices()
            for operation_values in seed_matrix for value in operation_values]


def expected_signature() -> int:
    signature = SIGNATURE_SEED
    checkpoint_count = ITERATIONS // CHECKPOINT_INTERVAL
    all_matrices = matrices()
    case_id = 0
    for seed_matrix in all_matrices:
        for checkpoint in range(checkpoint_count):
            for operation in range(OPERATION_COUNT):
                case_id += 1
                signature = signature_step(
                    signature, case_id, seed_matrix[operation][checkpoint])
    return signature


def emit_u32_array(name: str, values: list[int]) -> None:
    print(f"static const abi_u32 {name}[{len(values)}] = {{")
    for index in range(0, len(values), 4):
        line = ", ".join(
            f"0x{value:08x}UL" for value in values[index:index + 4])
        suffix = "," if index + 4 < len(values) else ""
        print(f"  {line}{suffix}")
    print("};")


def emit_corpus() -> None:
    expected = checkpoints_flat()
    print("#ifndef SEEDED_FAR_POINTER_CORPUS_INC")
    print("#define SEEDED_FAR_POINTER_CORPUS_INC")
    print()
    print(f"#define ABI_SEEDED_FAR_SUITE_ID {SUITE_ID}U")
    print(f"#define ABI_SEEDED_FAR_ITERATIONS {ITERATIONS}U")
    print(f"#define ABI_SEEDED_FAR_SEED_COUNT {len(SEEDS)}U")
    print(f"#define ABI_SEEDED_FAR_OPERATION_COUNT {OPERATION_COUNT}U")
    print(f"#define ABI_SEEDED_FAR_CHECKPOINT_INTERVAL {CHECKPOINT_INTERVAL}U")
    print("#define ABI_SEEDED_FAR_CHECKPOINTS_PER_OPERATION "
          f"{ITERATIONS // CHECKPOINT_INTERVAL}U")
    print(f"#define ABI_SEEDED_FAR_CHECKPOINT_COUNT {len(expected)}U")
    print("#define ABI_SEEDED_FAR_RESULT_COUNT "
          f"{len(SEEDS) * OPERATION_COUNT * ITERATIONS}UL")
    print("#define ABI_SEEDED_FAR_GROUP_SIGNATURE_SEED "
          f"0x{GROUP_SIGNATURE_SEED:08x}UL")
    print()
    emit_u32_array("abi_seeded_far_seeds", list(SEEDS))
    emit_u32_array("abi_seeded_far_expected", expected)
    print()
    print("#endif")


def main() -> None:
    global ITERATIONS, CHECKPOINT_INTERVAL, SEEDS, SUITE_ID

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "mode", choices=("corpus", "signature", "check-count",
                         "result-count"))
    parser.add_argument("--iterations", type=int, default=ITERATIONS)
    parser.add_argument("--checkpoint-interval", type=int,
                        default=CHECKPOINT_INTERVAL)
    parser.add_argument("--suite-id", type=int, default=SUITE_ID)
    parser.add_argument("--seed", action="append",
                        type=lambda value: int(value, 0), default=[])
    args = parser.parse_args()
    seeds = tuple(args.seed) if args.seed else SEEDS
    if not 1 <= args.iterations <= 32767:
        parser.error("--iterations must be in 1..32767")
    if (args.checkpoint_interval <= 0 or
            args.checkpoint_interval & (args.checkpoint_interval - 1)):
        parser.error("--checkpoint-interval must be a power of two")
    if args.iterations % args.checkpoint_interval:
        parser.error("--iterations must be divisible by --checkpoint-interval")
    if not seeds or any(not 1 <= seed <= MASK32 for seed in seeds):
        parser.error("each --seed must be a nonzero unsigned 32-bit value")
    checkpoint_count = (len(seeds) * OPERATION_COUNT *
                        (args.iterations // args.checkpoint_interval))
    if checkpoint_count > 4095:
        parser.error("checkpoint table must fit one 16 KiB Classic far object")
    if not 0 <= args.suite_id <= MASK16:
        parser.error("--suite-id must fit unsigned 16 bits")
    ITERATIONS = args.iterations
    CHECKPOINT_INTERVAL = args.checkpoint_interval
    SEEDS = seeds
    SUITE_ID = args.suite_id

    if args.mode == "corpus":
        emit_corpus()
    elif args.mode == "signature":
        print(expected_signature())
    elif args.mode == "check-count":
        print(checkpoint_count)
    else:
        print(len(SEEDS) * OPERATION_COUNT * ITERATIONS)


if __name__ == "__main__":
    main()
