import time
import random
import itertools

#import json
import orjson as json

from battleship_boards import place_ships


def load_random_subset(file_path, num_records):
    with open(file_path, "r") as f:
        total_lines = sum(1 for _ in f)
        f.seek(0)

        start_line = random.randint(0, total_lines - num_records)
        skipped_lines = itertools.islice(f, start_line)

        selected_lines = []
        for line in skipped_lines:
            try:
                parsed_board = json.loads(line.strip())
                selected_lines.append(parsed_board)
                if len(selected_lines) == num_records:
                    break
            except json.JSONDecodeError:
                continue

        return selected_lines


def generate_boards_ad_hoc(num_boards):
    return [place_ships() for _ in range(num_boards)]


def benchmark(scale):
    print(f"\nBenchmarking for {scale} boards:")

    start_time = time.time()
    ad_hoc_boards = generate_boards_ad_hoc(scale)
    ad_hoc_time = time.time() - start_time

    start_time = time.time()
    random_subset_boards = load_random_subset("battleship_boards_merge.json", scale)
    random_subset_time = time.time() - start_time

    print(f"\nAd hoc generation time: {ad_hoc_time:.2f} seconds")
    print(f"Random subset loading time: {random_subset_time:.2f} seconds")
    print(f"Efficiency gain: {ad_hoc_time / random_subset_time:.2f}x\n")


# Run the benchmark
for scale in [100, 1000, 10000, 100000, 1000000]:
    benchmark(scale)
