#!/usr/bin/env python3
"""Benchmark a running Assignment 4 server on loopback; requires an empty library.

Run the server in a fresh working directory. Use --smoke for a quick check.
A successful run prints its timings and score in seconds as one JSON object.
The driver inserts records and leaves them in the database.
"""
import argparse
import http.client
import json
import random
import statistics
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlencode

CLIENTS = 8
ROUNDS = 3
GENRES = ("Indie Rock", "Soft Folk", "Bluegrass", "Jazz", "Dance Pop")
WORDS = ("Night", "River", "Moon", "Blue", "Silver", "Summer")


def request(conn, method, path, status, payload=None):
    data = json.dumps(payload).encode() if payload is not None else None
    headers = {"Content-Type": "application/json"} if data is not None else {}
    conn.request(method, path, body=data, headers=headers)
    response = conn.getresponse()
    if response.status != status:
        raise ValueError(f"{method} {path}: expected HTTP {status}, got {response.status}")
    # Every planned query returns at most 32 small records.
    data = response.read(1_048_577)
    if len(data) > 1_048_576:
        raise ValueError(f"{method} {path}: response exceeds 1 MiB")
    return json.loads(data)


def parallel(port, count, operation):
    """Run eight persistent HTTP clients and stop issuing work after an error."""
    stop = threading.Event()

    def worker(offset):
        conn = http.client.HTTPConnection("127.0.0.1", port, timeout=15)
        try:
            for i in range(offset, count, CLIENTS):
                if stop.is_set():
                    break
                operation(conn, i)
        except Exception:
            stop.set()
            raise
        finally:
            conn.close()

    start = time.perf_counter()
    with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
        for future in as_completed([pool.submit(worker, i) for i in range(CLIENTS)]):
            future.result()
    return time.perf_counter() - start


def workload(count, queries_per_round, seed):
    """Precompute records and matching indexes before either timed phase."""
    rng = random.Random(seed)
    title_mask, artist_mask = rng.getrandbits(32), rng.getrandbits(32)
    artist_count = (count + 31) // 32
    entries = []
    for i in range(count):
        entries.append({
            "title": f"{rng.choice(WORDS)} [{(i // 16) ^ title_mask:08x}] take {i % 16 + 1:02}",
            "artist": f"The [{(i % artist_count) ^ artist_mask:08x}] Quartet",
            "genre": rng.choice(GENRES),
        })

    rounds = []
    for _ in range(ROUNDS):
        queries = []
        for q in range(queries_per_round):
            i = rng.randrange(count)
            group, artist = i // 16, i % artist_count
            title_term = f"[{group ^ title_mask:08X}]"
            artist_term = f"[{artist ^ artist_mask:08X}]"
            genre_term = entries[i]["genre"][1:].upper()
            # Fixed-width bracketed tags match a single title or artist group.
            # Enumerate that group's members, then check all literal filters.
            if q % 6 in (0, 1, 2):
                candidates = range(group * 16, min((group + 1) * 16, count))
                filters = {"title": title_term}
                if q % 6 == 1:
                    filters["genre"] = genre_term
                elif q % 6 == 2:
                    filters.update(artist=artist_term, genre=genre_term)
            elif q % 6 in (3, 4):
                candidates = range(artist, count, artist_count)
                filters = {"artist": artist_term}
                if q % 6 == 4:
                    filters["genre"] = genre_term
            else:
                candidates = ()
                filters = {"title": f"Unreleased {rng.getrandbits(32):08x}"}
            matches = [j for j in candidates if all(
                term.lower() in entries[j][key].lower() for key, term in filters.items()
            )]
            queries.append(("/songs/search?" + urlencode(filters), matches))
        rng.shuffle(queries)
        rounds.append(queries)
    return entries, rounds


def benchmark(port, seed, smoke):
    count, query_count = (120, 12) if smoke else (100_000, 300)
    conn = http.client.HTTPConnection("127.0.0.1", port, timeout=15)
    try:
        if request(conn, "GET", "/songs/search", 200) != []:
            raise ValueError("the benchmark requires an empty library; use a fresh server directory")
    finally:
        conn.close()

    entries, rounds = workload(count, query_count, seed)
    stored = [None] * count
    ids = set()
    lock = threading.Lock()

    def insert(conn, i):
        record = request(conn, "POST", "/songs/new", 201, entries[i])
        if not isinstance(record, dict) or type(record.get("id")) is not int:
            raise ValueError(f"insert {i}: expected a song with an integer ID")
        song_id = record["id"]
        expected = dict(entries[i], id=song_id, play_count=0)
        if type(record.get("play_count")) is not int or record != expected:
            raise ValueError(f"insert {i}: response differs from the song sent")
        with lock:
            if song_id in ids:
                raise ValueError(f"insert {i}: duplicate song ID {song_id}")
            ids.add(song_id)
        stored[i] = expected

    insert_time = parallel(port, count, insert)
    search_times = []
    for queries in rounds:
        def search(conn, i):
            path, matches = queries[i]
            rows = request(conn, "GET", path, 200)
            if not isinstance(rows, list) or len(rows) != len(matches):
                raise ValueError(f"{path}: incorrect number of results")
            expected = {stored[j]["id"]: stored[j] for j in matches}
            for row in rows:
                if (not isinstance(row, dict) or type(row.get("id")) is not int
                        or type(row.get("play_count")) is not int
                        or expected.pop(row["id"], None) != row):
                    raise ValueError(f"{path}: incorrect or duplicate song")
        search_times.append(parallel(port, query_count, search))

    return {
        "mode": "smoke" if smoke else "standard", "seed": seed, "songs": count,
        "clients": CLIENTS, "rounds": ROUNDS, "queries_per_round": query_count,
        "insert_seconds": insert_time, "search_seconds": search_times,
        "score_seconds": insert_time + statistics.median(search_times),
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, default=8080, help="loopback server port (default 8080)")
    parser.add_argument("--seed", type=int, default=1724, help="workload seed (default 1724)")
    parser.add_argument("--smoke", action="store_true", help="120 songs and 12 queries per round")
    args = parser.parse_args()
    if not 1 <= args.port <= 65535:
        parser.error("--port must be between 1 and 65535")
    try:
        print(json.dumps(benchmark(args.port, args.seed, args.smoke)))
    except (OSError, ValueError, http.client.HTTPException) as error:
        sys.exit(f"Benchmark failed: {error}")


if __name__ == "__main__":
    main()
