#! /usr/bin/env python

"""
Converts kinetics spreadsheet from 'E. coli WCM kinetic equations' google sheet
(Sheet1) to flat file for the model.

Process to generate updated file:
- Download latest data from google sheets and save as kinetics.tsv in this
directory (File -> Download -> Tab-separated values (.tsv, current sheet))
- Run this script: `reconstruction/metabolism_kinetics/convert_to_flat.py`
"""

import json
import os
import time

from wholecell.io import tsv
from wholecell.utils.filepath import ROOT_PATH

FILE_LOCATION = os.path.realpath(os.path.dirname(__file__))
INPUT_FILE = os.path.join(FILE_LOCATION, "kinetics.tsv")
OUTPUT_FILE = os.path.join(ROOT_PATH, "reconstruction", "ecoli", "flat", "metabolism_kinetics.tsv")

# Substitute units in headers to match units package format
UNIT_SUBS = {
    "(1/s)": "(1/units.s)",
    "(uM)": "(units.umol/units.L)",
}
# Strip all columns after this one
LAST_COLUMN = "customParameterVariables"
# Sort output by this column
SORT_COLUMN = "reactionID"
# Access first entry in list since only ever one enzyme
ENZYME_COLUMN = "enzymeID"


if __name__ == "__main__":
    data = []
    with open(INPUT_FILE, "rb") as f:
        print(f"Reading from {f.name}")
        reader = tsv.reader(f, quotechar="'")
        header = next(reader)

        n_cols = header.index(LAST_COLUMN) + 1  # number of columns to keep
        enzyme_col = header.index(ENZYME_COLUMN)
        header = header[:n_cols]
        for row in reader:
            d = ["" if entry == "null" else entry for entry in row[:n_cols]]
            enzymes = json.loads(d[enzyme_col])
            if len(enzymes) != 1:
                raise ValueError("Must have one enzyme per entry")
            d[enzyme_col] = f'"{enzymes[0]}"'
            data.append(d)

    # Replace readable units with package units in header labels
    for k, v in UNIT_SUBS.items():
        header = [h.replace(k, v) for h in header]

    # Sort by reaction ID
    sorted_data = sorted(data, key=lambda row_: row_[header.index(SORT_COLUMN)])

    # Save output with first column (literature reference) moved to the last column
    with open(OUTPUT_FILE, "wb") as f:
        print(f"Writing to {f.name}")
        writer = tsv.writer(f, quotechar="'", lineterminator="\n")
        writer.writerow([f"# Generated by {__file__} on {time.ctime()}"])
        writer.writerow(header[1:] + [header[0]])
        for row in sorted_data:
            writer.writerow(row[1:] + [f'"{row[0]}"'])
