#!/usr/bin/env python3
"""Hai goi khac nhau BAO NHIEU, va khi khac nhau thi AI DUNG?

Do tren 416 init kiem dinh, noi co quan trac de phan xu.  Day la cach quy doi
"+0.015 SEDI" thanh so quyet dinh thuc su doi, va thanh so lan doi DUNG/SAI.
"""
from __future__ import annotations

import argparse
import os
import sys

import numpy as np
from netCDF4 import Dataset

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import ehd_common as C


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--a", default=os.path.join(C.OUT, "operational",
                                                "forecast_valid.nc"))
    ap.add_argument("--b", default=os.path.join(C.OUT, "operational_ope1b",
                                                "forecast_valid.nc"))
    ap.add_argument("--name-a", default="PA1")
    ap.add_argument("--name-b", default="Ope1b")
    args = ap.parse_args()

    grid = C.Grid()
    npt = grid.npt
    st = np.load(os.path.join(C.OUT, "AI_Inp", "static.npz"), allow_pickle=True)
    yr = np.asarray(st["init_year"])
    # BIEN truoc DIEM -- reshape nham khong bao loi ma cho so sai trong hop ly
    T = np.memmap(os.path.join(C.OUT, "AI_Inp", "target.f4"), "f4", "r"
                  ).reshape(2080, C.NLT, 3, npt)
    iv = np.nonzero(np.isin(yr, C.VALID_YEARS))[0]
    E = np.asarray(T[iv][:, :, 2, :])            # evt, (416, 46, 541)

    na, nb = args.name_a, args.name_b
    print("A = %s   B = %s   (416 init x 541 o luoi = %d quyet dinh/cua so)"
          % (na, nb, iv.size * npt))
    print()
    print("%-4s %10s %8s | %10s %10s %10s | %9s" %
          ("W", "so o KHAC", "%", "B dung", "A dung", "ca hai sai", "loi ich rong"))
    for w, lts in C.WEEKS:
        obs = (np.nansum(E[:, lts, :], axis=1) >= 1.0)
        with Dataset(args.a) as d:
            pa = np.asarray(d["pred_%s" % w][:]).astype(bool)
        with Dataset(args.b) as d:
            pb = np.asarray(d["pred_%s" % w][:]).astype(bool)
        dis = pa != pb
        n = int(dis.sum())
        if n == 0:
            print("%-4s %10d %8.2f | %10s %10s %10s | %9s"
                  % (w, 0, 0.0, "-", "-", "-", "trung khit"))
            continue
        b_ok = int((dis & (pb == obs)).sum())
        a_ok = n - b_ok
        print("%-4s %10d %8.2f | %10d %10d %10s | %+9d"
              % (w, n, 100.0 * dis.mean(), b_ok, a_ok, "0", b_ok - a_ok))
    print("\n(Khi hai goi KHAC nhau thi mot ben dung mot ben sai -- khong the ca hai"
          "\n cung sai, vi quyet dinh la nhi phan. 'Loi ich rong' = so lan B dung"
          "\n tru so lan A dung.)")


if __name__ == "__main__":
    main()
