#!/usr/bin/env python3
"""List PositionRec/ and CashRecon/ files on port 2025 for the 5 funds, business date 2026-12-03."""
import json
import subprocess

PW = "opim_ops"
BD = "20261203"
FUNDS = ["TRIVISTA", "TWIN_SUMMIT", "SIMPLEWAY", "COUNTERWAVE", "ALTECA"]
OUT = "/Users/opimtech/.hermes/cache/scratch/pcr_files_20261203.json"

obscure = subprocess.run(
    ["rclone", "obscure", PW], capture_output=True, text=True, check=True
).stdout.strip()


def lsf(folder):
    remote = f":sftp,host=100.122.225.62,port=2025,user=hermes_ops:{folder}"
    try:
        r = subprocess.run(
            ["rclone", "lsf", remote,
             "--sftp-pass", obscure,
             "--sftp-known-hosts-file", "none",
             "--sftp-shell-type", "unix"],
            capture_output=True, text=True, timeout=60,
        )
    except subprocess.TimeoutExpired:
        return None, "TIMEOUT"
    if r.returncode != 0:
        err = (r.stderr.strip() or "ERROR rc=%d" % r.returncode)
        return None, err.splitlines()[-1][:200]
    return [x for x in r.stdout.splitlines() if x.strip()], None


result = {}
for fund in FUNDS:
    pos_files, pos_err = lsf(f"PositionRec/{fund}")
    cash_files, cash_err = lsf(f"CashRecon/{fund}")

    def pick(files, kw, date):
        if files is None:
            return None
        hit = [x for x in files if kw in x.lower() and date in x.lower()]
        strict = [x for x in hit if (kw + "_" + date) in x.lower()]
        return strict or hit

    pos_hit = pick(pos_files, "positionrec", BD) if pos_files is not None else None
    cash_hit = pick(cash_files, "cashrec", BD) if cash_files is not None else None

    result[fund] = {
        "position_files": pos_files,
        "position_error": pos_err,
        "cash_files": cash_files,
        "cash_error": cash_err,
        "position_match": pos_hit,
        "cash_match": cash_hit,
        "position_ok": bool(pos_hit),
        "cash_ok": bool(cash_hit),
    }

with open(OUT, "w") as f:
    json.dump(result, f, indent=2)

# Print a compact summary (file names included for eyeball verification)
for fund, r in result.items():
    print(f"== {fund}")
    print(f"  position: error={r['position_error']} files={r['position_files']}")
    print(f"  position_match={r['position_match']}")
    print(f"  cash: error={r['cash_error']} files={r['cash_files']}")
    print(f"  cash_match={r['cash_match']}")
    print(f"  position_ok={r['position_ok']} cash_ok={r['cash_ok']}")
print("saved:", OUT)
