"""Create an invented paired capture experiment for cell composition analysis."""

import csv
import hashlib
from pathlib import Path

import numpy as np


def write_table(path, fieldnames, rows):
    """Write a CSV with explicit column order and Unix line endings.

    Args:
        path: Destination CSV path.
        fieldnames: Ordered column names.
        rows: Dictionaries containing the table records.
    """
    with path.open("w", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames, lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def make_tables():
    """Generate paired counts and verify the latent reference ratios.

    Returns:
        Sample, count, and latent ratio records for the invented experiment.
    """
    rng = np.random.default_rng(20261114)
    cell_types = ["T_cells", "B_cells", "NK_cells", "Monocytes",
                  "pDC", "Unassigned"]
    baseline = np.array([0.51, 0.16, 0.12, 0.18, 0.00015, 0.02985])
    sample_rows = []
    count_rows = []
    truth_rows = []
    for donor_number in range(1, 21):
        donor_id = f"D{donor_number:02d}"
        control_weights = baseline * np.exp(rng.normal(0, 0.30, 6))
        treated_weights = control_weights.copy()
        monocyte_multiplier = 1.5 * np.exp(rng.normal(0, 0.18))
        treated_weights[3] *= monocyte_multiplier
        control_probability = control_weights / control_weights.sum()
        treated_probability = treated_weights / treated_weights.sum()
        ratio_change = np.log2(
            (treated_probability[1:4] / treated_probability[0])
            / (control_probability[1:4] / control_probability[0])
        )
        expected = np.array([0, 0, np.log2(monocyte_multiplier)])
        np.testing.assert_allclose(ratio_change, expected, atol=1e-14)
        for cell_type, change in zip(cell_types[1:4], ratio_change):
            truth_rows.append({"donor_id": donor_id,
                               "cell_type": cell_type,
                               "latent_log2_ratio_change": f"{change:.12f}"})
        for condition, probability in [
            ("Control", control_probability),
            ("Treated", treated_probability),
        ]:
            retained_cells = int(rng.integers(700, 4501))
            sample_id = f"{donor_id}_{condition.lower()}"
            sample_rows.append({"sample_id": sample_id,
                                "donor_id": donor_id,
                                "condition": condition,
                                "retained_cells": retained_cells})
            cell_counts = rng.multinomial(retained_cells, probability)
            assert cell_counts.sum() == retained_cells
            assert np.all(cell_counts[:4] > 0)
            for cell_type, count in zip(cell_types, cell_counts):
                count_rows.append({"sample_id": sample_id,
                                   "cell_type": cell_type,
                                   "cell_count": int(count)})
    return sample_rows, count_rows, truth_rows


def main():
    """Write the input tables and report their exact content hashes."""
    directory = Path(__file__).resolve().parent
    samples, counts, truth = make_tables()
    tables = [
        ("cell_abundance_samples.csv",
         ["sample_id", "donor_id", "condition", "retained_cells"], samples),
        ("cell_abundance_counts.csv",
         ["sample_id", "cell_type", "cell_count"], counts),
        ("cell_abundance_truth.csv",
         ["donor_id", "cell_type", "latent_log2_ratio_change"], truth),
    ]
    for filename, columns, rows in tables:
        path = directory / filename
        write_table(path, columns, rows)
        digest = hashlib.sha256(path.read_bytes()).hexdigest()
        print(f"{filename}: {len(rows)} rows; SHA-256 {digest}")


if __name__ == "__main__":
    main()
