#!/usr/bin/env python3
"""Original LockedIn Labs exercise: CPU model of CUDA work assignment.

Python 3.11+ standard library only. No CUDA, GPU, network or file writes.
The model is deliberately sequential: it teaches indices, not performance.
"""
import argparse
import unittest


def trace(length, block_size):
    if not isinstance(length, int) or isinstance(length, bool) or not 1 <= length <= 64:
        raise ValueError("Use 1–64 values in this teaching model.")
    if not isinstance(block_size, int) or isinstance(block_size, bool) or not 1 <= block_size <= 32:
        raise ValueError("Use 1–32 threads per teaching block.")
    host_a = list(range(1, length + 1))
    host_b = [value * 10 for value in host_a]
    # Copies make the two modeled memory locations explicit.
    device_a, device_b = host_a.copy(), host_b.copy()
    device_c = [None] * length  # Unwritten is not zero.
    blocks = (length + block_size - 1) // block_size
    assignments = []
    for block in range(blocks):
        for thread in range(block_size):
            index = block * block_size + thread
            active = index < length
            if active:  # This guard must precede every array access.
                device_c[index] = device_a[index] + device_b[index]
            assignments.append((block, thread, index, active))
    # This CPU loop has completed. Real GPU submission needs synchronization
    # and launch/execution error handling before the host consumes the result.
    host_c = device_c.copy()
    reference = [left + right for left, right in zip(host_a, host_b)]
    if host_c != reference:
        raise RuntimeError("The trace disagrees with the independent CPU reference.")
    return host_a, host_b, host_c, assignments


class TraceChecks(unittest.TestCase):
    def test_boundaries_and_grouping(self):
        for length in (1, 6, 9, 31, 32, 33, 64):
            for block_size in (1, 4, 8, 32):
                with self.subTest(length=length, block_size=block_size):
                    _, _, result, assignments = trace(length, block_size)
                    self.assertEqual(result, [11 * value for value in range(1, length + 1)])
                    written = [index for _, _, index, active in assignments if active]
                    self.assertEqual(sorted(written), list(range(length)))
                    skipped = [index for _, _, index, active in assignments if not active]
                    self.assertTrue(all(index >= length for index in skipped))
                    self.assertLess(len(skipped), block_size)

    def test_rejects_unbounded_or_invalid_inputs(self):
        for length, block in ((0, 4), (-1, 4), (65, 4), (6, 0), (6, 33), (1.5, 4), (True, 4)):
            with self.subTest(length=length, block=block), self.assertRaises(ValueError):
                trace(length, block)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--length", type=int, default=6, help="Values per array, 1–64")
    parser.add_argument("--block-size", type=int, default=4, help="Threads per teaching block, 1–32")
    parser.add_argument("--check", action="store_true", help="Check the CPU model's boundaries and grouping")
    args = parser.parse_args()
    if args.check:
        result = unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(TraceChecks))
        return 0 if result.wasSuccessful() else 1
    try:
        a, b, c, assignments = trace(args.length, args.block_size)
    except ValueError as error:
        parser.error(str(error))
    print("CPU-ONLY TEACHING TRACE — no CUDA execution or GPU timing")
    print(f"1. Host prepares A={a} and B={b}")
    print("2. Copy inputs to modeled device buffers; C starts unwritten.")
    print(f"3. Grid: {len(assignments) // args.block_size} blocks x {args.block_size} threads")
    for block, thread, index, active in assignments:
        action = f"C[{index}] = {a[index]} + {b[index]} = {c[index]}" if active else "SKIP: no array access"
        print(f"   block {block}, thread {thread}: i={index}; {action}")
    print("4. Completion boundary, then copy result to host and compare.")
    print(f"   C={c}; matches CPU reference")
    print("This result checks index assignment only, not hardware compatibility or speed.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
