#!/usr/bin/env python3
"""Reproduce storage-link accounting ceilings, not measured application throughput.

The first ten CSV columns preserve the original interface dataset contract.
For PCIe 6/7 their legacy 'payload' fields count TLP+DLP (242/256 bytes).
The appended region fields instead count the TLP region (236/256 bytes),
which still includes transaction headers. See the JSON metadata for sources.
"""
import argparse
import csv
import math
from fractions import Fraction
from pathlib import Path
from xml.sax.saxutils import escape

# interface, generation, year, raw bit-equivalent GT/s, legacy code, numerator,
# denominator, example width, historical source ID
R = [
    ("SATA", "1.0", 2003, 1.5, "8b/10b", 8, 10, 1, "sata"),
    ("SATA", "2.0", 2004, 3.0, "8b/10b", 8, 10, 1, "sata"),
    ("SATA", "3.0", 2009, 6.0, "8b/10b", 8, 10, 1, "sata"),
    ("SAS", "SAS-1", 2004, 3.0, "8b/10b", 8, 10, 1, "sas"),
    ("SAS", "SAS-2", 2010, 6.0, "8b/10b", 8, 10, 1, "sas"),
    ("SAS", "SAS-3", 2014, 12.0, "8b/10b", 8, 10, 1, "sas"),
    ("SAS", "SAS-4 (24G)", 2019, 22.5, "128b/150b", 128, 150, 1, "sas"),
    ("PCIe", "1.0", 2003, 2.5, "8b/10b", 8, 10, 4, "pcie"),
    ("PCIe", "2.0", 2007, 5.0, "8b/10b", 8, 10, 4, "pcie"),
    ("PCIe", "3.0", 2010, 8.0, "128b/130b", 128, 130, 4, "pcie"),
    ("PCIe", "4.0", 2017, 16.0, "128b/130b", 128, 130, 4, "pcie"),
    ("PCIe", "5.0", 2019, 32.0, "128b/130b", 128, 130, 4, "pcie"),
    ("PCIe", "6.0", 2022, 64.0, "242B/256B FLIT", 242, 256, 4, "pcie"),
    ("PCIe", "7.0", 2025, 128.0, "242B/256B FLIT", 242, 256, 4, "pcie"),
]
LEGACY_HEADER = [
    "interface", "generation", "spec_year", "line_rate_gtps", "line_code",
    "coding_efficiency_percent", "lanes", "payload_gbps_per_lane",
    "payload_mb_s_per_lane", "payload_mb_s_link",
]
HEADER = LEGACY_HEADER + [
    "accounting_boundary", "region_numerator", "region_denominator",
    "region_mb_s_per_lane", "region_mb_s_link", "region_source_id",
]
SLUG = "storage-interface-payload-ceilings"
FLIT_LAYOUT = {"tlp": 236, "dlp": 6, "crc": 8, "fec": 6}


def round_half_up(value):
    value = Fraction(value)
    return (2 * value.numerator + value.denominator) // (2 * value.denominator)


def build_rows():
    result = []
    for interface, gen, year, rate, code, p, c, lanes, source in R:
        raw = Fraction(str(rate))
        legacy = raw * Fraction(p, c)
        flit = interface == "PCIe" and gen in ("6.0", "7.0")
        numerator = FLIT_LAYOUT["tlp"] if flit else p
        denominator = sum(FLIT_LAYOUT.values()) if flit else c
        region = raw * Fraction(numerator, denominator)
        result.append([
            interface, gen, year, f"{rate:g}", code, f"{p / c * 100:.2f}",
            lanes, f"{float(legacy):.3f}", round_half_up(legacy * 125),
            round_half_up(legacy * 125 * lanes),
            "tlp-region" if flit else "line-code-region",
            numerator, denominator, round_half_up(region * 125),
            round_half_up(region * 125 * lanes),
            "pcie-flit-2025" if flit else source + "-wiki",
        ])
    return result


def chart(rows):
    colors = {"SATA": "#c0392b", "SAS": "#2e8b57", "PCIe": "#1b6ca8"}
    width, left, right, top, row_height = 760, 200, 90, 80, 22
    height = top + len(rows) * row_height + 56

    def sx(value):
        return left + (math.log10(value) - 2) / 3 * (width - left - right)

    svg = [
        f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" width="{width}" height="{height}" role="img" aria-labelledby="title desc" font-family="sans-serif" font-size="12">',
        '<title id="title">Storage-link transfer-region ceilings, one direction, MB/s</title>',
        '<desc id="desc">Log scale. SATA and SAS use one lane; PCIe uses four. PCIe 6 and 7 count only the TLP region, including headers, not application data. Other rows count the line-code region.</desc>',
        f'<rect width="{width}" height="{height}" fill="#fff"/>',
        '<text x="10" y="22" font-size="15" font-weight="bold">Transfer-region ceiling per link (MB/s, log scale)</text>',
        '<text x="10" y="40" fill="#444">SATA and SAS: one lane. PCIe: four lanes. One direction; not device throughput.</text>',
        '<text x="10" y="58" fill="#444">PCIe 6/7: TLP region including headers. Other rows: after line coding.</text>',
    ]
    for tick in (100, 1000, 10000, 100000):
        svg.append(f'<line x1="{sx(tick):.1f}" y1="{top-6}" x2="{sx(tick):.1f}" y2="{height-44}" stroke="#ddd"/><text x="{sx(tick):.1f}" y="{height-30}" text-anchor="middle">{tick:,}</text>')
    for k, row in enumerate(rows):
        y = top + k * row_height
        value = row[14]
        label = escape(row[0] + " " + row[1] + (" x4" if row[0] == "PCIe" else ""))
        svg.append(f'<text x="{left-8}" y="{y+14}" text-anchor="end">{label}</text>')
        svg.append(f'<rect x="{left}" y="{y+3}" width="{sx(value)-left:.1f}" height="15" fill="{colors[row[0]]}"/><text x="{sx(value)+5:.1f}" y="{y+15}" font-size="11">{value:,}</text>')
    svg.append(f'<text x="{(left+width-right)/2}" y="{height-8}" text-anchor="middle">MB/s (10^6 bytes per second), log axis</text></svg>')
    return "\n".join(svg) + "\n"


def generate(directory):
    directory.mkdir(parents=True, exist_ok=True)
    rows = build_rows()
    with (directory / f"{SLUG}.csv").open("w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(HEADER)
        writer.writerows(rows)
    (directory / f"{SLUG}.svg").write_text(chart(rows), encoding="utf-8")
    (directory / "build-interface-ceilings.py").write_bytes(Path(__file__).read_bytes())


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    project_data = Path(__file__).resolve().parent.parent / "public/data/datasets"
    default_output = project_data if project_data.is_dir() else Path.cwd()
    parser.add_argument("--output-dir", type=Path, default=default_output)
    generate(parser.parse_args().output_dir)
