"""Shared paths, labelled values and readers for the Stage 1 v3 requirements agent (part B).
Every number is a V(value, label, src): label S (read on the page or file itself), E (estimated from S/E inputs) or
A (rests on an assumption). C() derives a value: its label is A if any input is A, else E; its src joins the inputs'
srcs and the script. Paths are relative to this folder (stage1-v3/requirements) or to stage1-v2 / stage1-v3/repair."""
import json, math, os
import pandas as pd

HERE = os.path.dirname(os.path.abspath(__file__))
RQ = os.path.dirname(HERE)                                  # stage1-v3/requirements
V3 = os.path.dirname(RQ)                                    # stage1-v3
ROOT = os.path.dirname(V3)
V2 = os.path.join(ROOT, 'stage1-v2')
R = os.path.join(V3, 'repair')
WORK = os.path.join(RQ, 'work')
RAW = os.path.join(RQ, 'raw')
os.makedirs(WORK, exist_ok=True)

LAYERS = ['C01', 'C02', 'C03', 'C04', 'C05', 'C06', 'C07', 'C08', 'C09', 'C10', 'C11', 'C12', 'C13', 'C14', 'C15',
          'U1', 'U2', 'U3', 'U4']
NO_PROD = ('U2', 'U4')          # net purchases abroad, net exports: accounting rows with no production, no input need
ACCOUNTING = ('U1', 'U2', 'U3', 'U4')


class V:
    __slots__ = ('v', 'l', 's')

    def __init__(self, v, l, s):
        assert l in ('S', 'E', 'A'), l
        self.v, self.l, self.s = float(v), l, s

    def __repr__(self):
        return f'{self.v:.6g}[{self.l}]'


def _join(*ss):
    out = []
    for s in ss:
        for t in str(s).split(';'):
            t = t.strip()
            if t and t not in out:
                out.append(t)
    return ';'.join(out)


def C(v, *deps, code, label=None):
    lab = label or ('A' if any(d.l == 'A' for d in deps) else 'E')
    return V(v, lab, _join(*[d.s for d in deps], code))


def A(v, sid):
    return V(v, 'A', sid)


def S(v, sid):
    return V(v, 'S', sid)


def E(v, sid):
    return V(v, 'E', sid)


def r6(x):
    if x is None or (isinstance(x, float) and (math.isnan(x) or math.isinf(x))):
        return None
    return float(f'{x:.10g}') if abs(x) < 1e15 else x


def cells(d, col, x):
    """Write V x into dict d as col, col_label, col_src (blank when x is None)."""
    if x is None:
        d[col], d[col + '_label'], d[col + '_src'] = None, '', ''
    else:
        d[col], d[col + '_label'], d[col + '_src'] = r6(x.v), x.l, x.s


# ------------------------------------------------------------------ readers (read-only inputs, read in place)
def rcsv(*p):
    return pd.read_csv(os.path.join(*p))


def lay_v(df, L, col, pfx, fname):
    return V(df.loc[L, col], df.loc[L, col + '_label'], f'{pfx}:{fname}:{L}')


LAY = rcsv(R, 'baseline', 'layers.csv').set_index('id')                 # R: repaired baseline by layer
TOT = rcsv(R, 'baseline', 'totals.csv').set_index('id')
GL = rcsv(V2, 'v1', 'bridge', 'gap_by_layer.csv').set_index('id')        # B: v1 income-elasticity split
BMAC = rcsv(V2, 'v1', 'bridge', 'bridge_macro.csv').set_index('id')
BOT = rcsv(R, 'agent4_bottlenecks', 'bottlenecks.csv').set_index('id')  # R: Agent 4 rerun
NBL = rcsv(R, 'agent4_bottlenecks', 'work', 'need_by_layer.csv')
MEMO = json.load(open(os.path.join(R, 'agent4_bottlenecks', 'work', 'model_memo.json')))
MEMOCSV = rcsv(R, 'agent4_bottlenecks', 'work', 'memo.csv').set_index('id')
DRV = rcsv(R, 'baseline', 'drivers.csv').set_index('id')
LI = rcsv(V2, 'agent4_bottlenecks', 'work', 'layer_intensity.csv').set_index('layer_id')   # A4: EXIOBASE footprints
M2SUM = rcsv(V2, 'merge', 'summary.csv').set_index('item')
BLV2 = rcsv(V2, 'baseline', 'totals.csv').set_index('id')


def BM(i):
    return V(BMAC.loc[i, 'value'], BMAC.loc[i, 'value_label'], f'B:bridge_macro.csv:{i}')


def D(i):
    return V(DRV.loc[i, 'value'], DRV.loc[i, 'value_label'], f'R:baseline/drivers.csv:{i}')


def T(i, col='value_ppp_bn'):
    return V(TOT.loc[i, col], TOT.loc[i, col + '_label'], f'R:baseline/totals.csv:{i}')


def LY(L, col):
    return lay_v(LAY, L, col, 'R', 'baseline/layers.csv')


def BT(k, col):
    """A value from the repaired Agent 4 bottlenecks.csv (R:)."""
    return V(BOT.loc[k, col], BOT.loc[k, col + '_label'], f'R:agent4_bottlenecks/bottlenecks.csv:{k}')


def PPF(L):
    return V(GL.loc[L, 'ppp_factor'], GL.loc[L, 'ppp_factor_label'], 'B:gap_by_layer.csv:ppp_factor')


def NB(k, L, col='intensity_unit_per_ppp_bn'):
    row = NBL[(NBL.input_id == k) & (NBL.layer_id == L)]
    if row.empty:
        return None
    lab = 'E' if col == 'intensity_unit_per_ppp_bn' else row.iloc[0][col + '_label']
    return V(row.iloc[0][col], lab, f'R:agent4_bottlenecks/work/need_by_layer.csv:{k}')


def MM(key, L=None):
    """A value from the repaired Agent 4 model_memo.json (R:)."""
    x = MEMO[key] if L is None else MEMO[key][L]
    if isinstance(x, dict):
        return V(x['v'], x['l'], 'R:agent4_bottlenecks/work/model_memo.json')
    return V(x, 'E', 'R:agent4_bottlenecks/work/model_memo.json')


def MC(i):
    return V(MEMOCSV.loc[i, 'value'], MEMOCSV.loc[i, 'value_label'], f'R:agent4_bottlenecks/work/memo.csv:{i}')


EXIO = 'A4:S52;A4:A09;A4:work/layer_intensity.csv'


def LIv(L, col):
    return V(LI.loc[L, col], 'E', EXIO)
