"""Market data and calculation inputs: integrity checks of the base (Market Data Standard v1.0, section "Checks").

MD-1  latest quotes file: every row has a date, a currency and a close above zero; no date after the latest complete US session;
    rows older than 5 trading days are listed (WARN: a listing that no longer trades or a feed gap).
MD-2  private input archive: the manifest is an append log in fetch order; the latest line of every file matches its SHA-256.
MD-3  daily history files (value per MW, miner NAV, market marks): dates strictly increase, no duplicate dates;
    with --base REF, every row of the earlier version dated before the newest date of the current file is kept unchanged
    (earlier sessions are never rewritten; a same-day re-run may replace only its own session's row; a documented correction
    in src/data/mining/corrections.csv is the only exception).
MD-4  latest daily files: the date of each JSON file equals the newest row of its history file; the bitcoin close is the same in all three.
MD-5  interim inputs from filings: required columns filled, source link present, entry time not before the figure's date,
    no exact duplicate rows; with --base REF, no earlier row is deleted or changed (corrections are new rows).
MD-6  frozen calculation inputs: every market snapshot of a valuation base matches the SHA-256 recorded in its meta file.
MD-7  freshness register present and dated within 4 days of the run.

Exit 1 if any ERROR (nothing is changed by this script). Usage: python3 tools/market_data_check.py [--base origin/main] [--json out.json]
"""
import csv, datetime as dt, glob, hashlib, io, json, os, subprocess, sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA = os.path.join(ROOT, 'src', 'data'); MD = os.path.join(DATA, 'mining'); ARCH = os.path.join(ROOT, 'archive', 'inputs')
sys.path.insert(0, os.path.join(ROOT, 'tools'))
res = []
def add(level, check, msg): res.append({'level': level, 'check': check, 'message': msg})
def sha(p): return hashlib.sha256(open(p, 'rb').read()).hexdigest()
def rd(p): return list(csv.DictReader(open(p, encoding='utf-8', newline='')))
def at_base(ref, rel):
    try:
        return subprocess.run(['git', '-C', ROOT, 'show', f'{ref}:{rel}'], capture_output=True, text=True, check=True).stdout
    except subprocess.CalledProcessError:
        return None

args = sys.argv[1:]
BASE = args[args.index('--base') + 1] if '--base' in args else None
OUTJ = args[args.index('--json') + 1] if '--json' in args else None
now = dt.datetime.now(dt.timezone.utc)
try:
    from market_session import expected_session
    exp = expected_session()
    exp = dt.date.fromisoformat(str(exp)[:10])
except Exception:
    exp = (now - dt.timedelta(hours=21, minutes=30)).date()
    while exp.weekday() > 4: exp -= dt.timedelta(days=1)
def bdays_between(a, b):
    n, d = 0, a
    while d < b:
        d += dt.timedelta(days=1)
        if d.weekday() < 5: n += 1
    return n

# MD-1 latest quotes
qp = os.path.join(DATA, 'quotes_latest.csv')
if not os.path.exists(qp): add('ERROR', 'MD-1', 'src/data/quotes_latest.csv missing')
else:
    Q = rd(qp); old = []
    for r in Q:
        if not r.get('quote_date') or not r.get('currency'): add('ERROR', 'MD-1', f"{r.get('ticker')}: date or currency missing"); continue
        try: c = float(r['close'])
        except (TypeError, ValueError): c = None
        if c is None or c <= 0: add('ERROR', 'MD-1', f"{r['ticker']} {r['quote_date']}: close {r.get('close')!r} is not a positive number")
        d = dt.date.fromisoformat(r['quote_date'][:10])
        if d > exp: add('ERROR', 'MD-1', f"{r['ticker']}: quote date {d} is after the latest complete US session {exp} (intraday print)")
        elif bdays_between(d, exp) > 5: old.append(f"{r['ticker']} {d}")
    if old: add('WARN', 'MD-1', f"{len(old)} of {len(Q)} listings have no close in the last 5 trading days: {', '.join(old[:12])}")
    add('INFO', 'MD-1', f"{len(Q)} listings; latest complete US session {exp}")

# MD-2 private archive
mp = os.path.join(ARCH, 'manifest.csv')
if os.path.exists(mp):
    M = rd(mp); prev = ''; last = {}
    for r in M:   # the manifest is an append log in fetch order; a restated day appends a new line for the same file
        if r['fetched_utc'] < prev: add('ERROR', 'MD-2', f"manifest fetch times go backwards at {r['file']} ({r['fetched_utc']} after {prev})")
        prev = r['fetched_utc']; last[r['file']] = r
    for f, r in sorted(last.items()):
        p = os.path.join(ARCH, f)
        if not os.path.exists(p): add('ERROR', 'MD-2', f"archive file missing: {f}")
        elif sha(p) != r['sha256']: add('ERROR', 'MD-2', f"archive SHA-256 differs from the latest manifest line: {f}")
    sup = len(M) - len(last)
    add('INFO', 'MD-2', f"{len(last)} archived input files, last {max(r['as_of'] for r in last.values())}"
        + (f"; {sup} superseded line(s) from restated days (earlier versions are in the git history)" if sup else ''))
else: add('WARN', 'MD-2', 'archive/inputs/manifest.csv missing')

# documented corrections of earlier rows (src/data/mining/corrections.csv): the only way an earlier session may change
CP = os.path.join(MD, 'corrections.csv')
CORR = {(r['file'], r['row_date']) for r in rd(CP)} if os.path.exists(CP) else set()
if os.path.exists(CP):
    for i, r in enumerate(rd(CP), 2):
        if not all((r.get(k) or '').strip() for k in ('entered', 'file', 'row_date', 'fields', 'reason', 'entered_by')): add('ERROR', 'MD-3', f'corrections.csv line {i}: empty field')

# MD-3 + MD-4 history files
H = {'capacity_daily_history.csv': 'capacity_daily.json', 'nav_daily_history.csv': 'nav_daily.json', 'market_marks_history.csv': 'market_marks.json'}
btc = {}
for hf, jf in H.items():
    p = os.path.join(MD, hf); rel = os.path.relpath(p, ROOT)
    if not os.path.exists(p): add('ERROR', 'MD-3', f'{rel} missing'); continue
    rows = rd(p); ds = [r['date'] for r in rows]
    if any(b <= a for a, b in zip(ds, ds[1:])): add('ERROR', 'MD-3', f'{hf}: dates not strictly increasing or duplicated')
    if BASE:
        txt = at_base(BASE, rel)
        if txt is not None and rows:
            last = ds[-1]; cur = {r['date']: r for r in rows}
            for r in csv.DictReader(io.StringIO(txt)):
                if r['date'] < last and cur.get(r['date']) != r and (hf, r['date']) not in CORR:
                    add('ERROR', 'MD-3', f"{hf}: the row of {r['date']} was rewritten or deleted against {BASE}"); break
    jp = os.path.join(MD, jf)
    if os.path.exists(jp) and rows:
        J = json.load(open(jp, encoding='utf-8'))
        jd = J.get('as_of') or J.get('date') or (J.get('btc') or {}).get('date')
        if jd and str(jd)[:10] != ds[-1]: add('ERROR', 'MD-4', f'{jf} is dated {jd} but the newest row of {hf} is {ds[-1]}')
        b = rows[-1].get('btc_usd')
        if b: btc[hf] = round(float(b), 2)
    add('INFO', 'MD-3', f'{hf}: {len(rows)} sessions, {ds[0] if ds else "-"} to {ds[-1] if ds else "-"}')
lastd = {}
for hf in H:
    p = os.path.join(MD, hf)
    if os.path.exists(p):
        rr = rd(p)
        if rr: lastd[hf] = rr[-1]['date']
if len(set(lastd.values())) == 1 and len(set(btc.values())) > 1:
    add('ERROR', 'MD-4', f'bitcoin close differs between the daily files of the same session: {btc}')

# MD-5 interim inputs
ip = os.path.join(MD, 'interim_inputs.csv'); irel = os.path.relpath(ip, ROOT)
if os.path.exists(ip):
    I = rd(ip); seen = set()
    for i, r in enumerate(I, 2):
        miss = [k for k in ('entered', 'ticker', 'field', 'value', 'as_of', 'source_form', 'source_url') if not (r.get(k) or '').strip()]
        if miss: add('ERROR', 'MD-5', f'interim_inputs.csv line {i}: empty {miss}')
        if r.get('entered') and r.get('as_of') and r['entered'][:10] < r['as_of'][:10]: add('ERROR', 'MD-5', f'interim_inputs.csv line {i}: entered {r["entered"][:10]} before the figure date {r["as_of"]}')
        if r.get('source_url') and not r['source_url'].startswith('https://'): add('ERROR', 'MD-5', f'interim_inputs.csv line {i}: source link is not an https address')
        key = tuple(r.get(k) for k in ('ticker', 'field', 'value', 'as_of', 'accession'))
        if key in seen: add('WARN', 'MD-5', f'interim_inputs.csv line {i}: duplicate of an earlier row {key[:4]}')
        seen.add(key)
    if BASE:
        txt = at_base(BASE, irel)
        if txt is not None:
            now_rows = {json.dumps(r, sort_keys=True) for r in I}
            gone = [r for r in csv.DictReader(io.StringIO(txt)) if json.dumps(r, sort_keys=True) not in now_rows]
            if gone: add('ERROR', 'MD-5', f'interim_inputs.csv: {len(gone)} earlier row(s) deleted or changed against {BASE} (a correction is a new row)')
    add('INFO', 'MD-5', f'{len(I)} interim input rows')

# MD-6 frozen snapshots
for meta in sorted(glob.glob(os.path.join(ROOT, 'bases', '*', 'config', 'market_snapshot_meta.json'))):
    m = json.load(open(meta, encoding='utf-8')); f = os.path.join(os.path.dirname(meta), m['file'])
    if not os.path.exists(f): add('ERROR', 'MD-6', f'{os.path.relpath(f, ROOT)} missing')
    elif sha(f) != m['sha256']: add('ERROR', 'MD-6', f'{os.path.relpath(f, ROOT)}: SHA-256 differs from its meta file (a frozen snapshot was edited)')
    else: add('INFO', 'MD-6', f"{os.path.relpath(f, ROOT)} frozen at {m.get('as_of')} from commit {str(m.get('source_commit'))[:7]}")

# MD-7 freshness register
fp = os.path.join(DATA, 'freshness.json')
if not os.path.exists(fp): add('ERROR', 'MD-7', 'src/data/freshness.json missing')
else:
    F = json.load(open(fp, encoding='utf-8')); rd_ = F.get('run_date')
    if not rd_ or (now.date() - dt.date.fromisoformat(rd_)).days > 4: add('WARN', 'MD-7', f'freshness register run date {rd_} is more than 4 days old')
    stale = [i for i in F.get('items', []) if i.get('status') not in ('OK', None)]
    add('INFO', 'MD-7', f"freshness register {rd_}: {len(stale)} input(s) past their limit or without data")

order = {'ERROR': 0, 'WARN': 1, 'INFO': 2}
for r in sorted(res, key=lambda r: (order[r['level']], r['check'])): print(f"{r['level']:5} {r['check']:5} {r['message']}")
e = sum(r['level'] == 'ERROR' for r in res); w = sum(r['level'] == 'WARN' for r in res)
print(f"market data check: {e} error(s), {w} warning(s)")
if OUTJ: json.dump({'schema': 'hashflops.market-data-check/1', 'run_utc': now.strftime('%Y-%m-%dT%H:%MZ'), 'errors': e, 'warnings': w, 'results': res}, open(OUTJ, 'w'), indent=1)
sys.exit(1 if e else 0)
