#!/usr/bin/env python3
"""Aeolipile offline command line. Standard library only (python3 -I).

  python3 -I aeo_cli.py run --cohort SYN-A.csv [--config cfg.json] [--hourly out.csv]
  python3 -I aeo_cli.py threshold --cohort SYN-A.csv --field forced_curtailment --lo 0 --hi 1 --ceiling 130
  python3 -I aeo_cli.py fixtures --fixtures s-syn.json --cohort-dir cohorts --report parity-report.json

`run` prints the result, the trace hash and the result digest as JSON.
`fixtures` reruns every fixture and compares with the published report.
A config file holds any subset of the ABI fields; the rest take defaults.
"""
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import aeo_core as k  # noqa: E402

SPECIAL = {"NaN": float("nan"), "Infinity": float("inf"), "-Infinity": float("-inf")}


def arg(argv, name, default=None):
    if name in argv and argv.index(name) + 1 < len(argv):
        return argv[argv.index(name) + 1]
    return default


def load(argv):
    cfg = k.default_config()
    if arg(argv, "--config"):
        with open(arg(argv, "--config"), "r", encoding="utf-8") as f:
            cfg.update(json.load(f))
    with open(arg(argv, "--cohort"), "rb") as f:
        code, locus, series = k.parse_cohort_csv(f.read())
    if code != k.AEO_OK:
        raise SystemExit("cohort refused: code %d at %s" % (code, k.describe_locus(code, locus)))
    code, locus, wire = k.config_to_wire(cfg)
    if code != k.AEO_OK:
        raise SystemExit("config refused: code %d at %s" % (code, k.describe_locus(code, locus)))
    return wire, series


def cmd_run(argv):
    wire, series = load(argv)
    hourly = [] if arg(argv, "--hourly") else None
    out = k.run(wire, series, hourly)
    if out["code"] != k.AEO_OK:
        print(json.dumps({"code": out["code"], "locus": k.describe_locus(out["code"], out["locus"])}))
        return 1
    if hourly is not None:
        with open(arg(argv, "--hourly"), "w", encoding="utf-8", newline="\n") as f:
            f.write("hour," + ",".join(k.HOURLY_NAMES) + "\n")
            for h, row in enumerate(hourly):
                f.write("%d,%s\n" % (h, ",".join(repr(v) for v in row)))
    print(json.dumps({"abi": k.AEO_ABI_VERSION, "result": k.result_dict(out),
                      "trace_fnv1a64": out["trace"], "digest_fnv1a64": out["digest"]}, indent=2))
    return 0


def cmd_threshold(argv):
    wire, series = load(argv)
    print(json.dumps(k.find_threshold(wire, series, arg(argv, "--field"), float(arg(argv, "--lo")),
                                      float(arg(argv, "--hi")), float(arg(argv, "--ceiling")),
                                      arg(argv, "--metric", "adj_cost_usd_mwh")), indent=2))
    return 0


def cmd_fixtures(argv):
    with open(arg(argv, "--fixtures", "s-syn.json"), "r", encoding="utf-8") as f:
        cases = json.load(f)["cases"]
    with open(arg(argv, "--report", "parity-report.json"), "r", encoding="utf-8") as f:
        published = {c["id"]: c for c in json.load(f)["cases"]}
    cohort_dir = arg(argv, "--cohort-dir", "cohorts")
    cache = {}
    bad = 0
    for case in cases:
        if case["cohort"] not in cache:
            with open(os.path.join(cohort_dir, case["cohort"] + ".csv"), "rb") as f:
                cache[case["cohort"]] = k.parse_cohort_csv(f.read())[2]
        cfg = k.default_config()
        for key, value in case["config"].items():
            cfg[key] = SPECIAL[value] if isinstance(value, str) else value
        series = [list(s) for s in cache[case["cohort"]]]
        for p in case["patches"]:
            s = k.SERIES_NAMES.index(p["series"])
            v = p.get("value")
            v = SPECIAL[v] if isinstance(v, str) else v
            if p["op"] == "set":
                series[s][p["index"]] = v
            elif p["op"] == "fill":
                series[s] = [v] * len(series[s])
            elif p["op"] == "truncate":
                series[s] = series[s][:p["length"]]
            elif p["op"] == "append":
                series[s].append(v)
        code, locus, wire = k.config_to_wire(cfg)
        out = k.run(wire, series) if code == k.AEO_OK else {"code": code, "locus": locus}
        want = published[case["id"]]
        same = out["code"] == want["code"] and out.get("trace", "-") == want["trace"] \
            and out.get("digest", "-") == want["digest"]
        if not same:
            bad += 1
            print("MISMATCH", case["id"])
    print("%d fixtures, %d mismatches against the published report" % (len(cases), bad))
    return 1 if bad else 0


def main(argv):
    commands = {"run": cmd_run, "threshold": cmd_threshold, "fixtures": cmd_fixtures}
    if len(argv) < 2 or argv[1] not in commands:
        print(__doc__)
        return 2
    return commands[argv[1]](argv)


if __name__ == "__main__":
    sys.exit(main(sys.argv))
