#!/usr/bin/env python3
import os
import math
import json
from pathlib import Path
from datetime import datetime, timezone

import numpy as np

ROOT = Path("/var/www/vps2.happyuser.info/dex")
ENV_PATH = ROOT / "DEX_REPORTS/live_check_manual_25/current_position.env"
NPZ_PATH = ROOT / "DEX_DATA/fast_npz/base_CHECK_USDC_2PCT_fresh_fee_replay_v2.npz"
OUT_DIR = ROOT / "DEX_REPORTS/live_check_manual_25"
OUT_DIR.mkdir(parents=True, exist_ok=True)

def read_env(path):
    d = {}
    for line in path.read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        d[k.strip()] = v.strip()
    return d

env = read_env(ENV_PATH)

deposited_usdc = float(env["DEPOSITED_USDC"])
deposited_check = float(env["DEPOSITED_CHECK"])
range_low = float(env["RANGE_LOW_CHECK_PER_USDC"])
range_high = float(env["RANGE_HIGH_CHECK_PER_USDC"])

z = np.load(NPZ_PATH, allow_pickle=True)

# NPZ price = USDC per CHECK.
price_usdc_per_check = float(z["price"][-1])

# UI / Uniswap-style price for token0=USDC, token1=CHECK:
# CHECK per USDC.
price_check_per_usdc = 1.0 / price_usdc_per_check

initial_value_usd = deposited_usdc + deposited_check * price_usdc_per_check

pa = range_low
pb = range_high
p = price_check_per_usdc

sqrt_pa = math.sqrt(pa)
sqrt_pb = math.sqrt(pb)
sqrt_p0 = math.sqrt(p)

# Estimate liquidity from the original deposit.
# token0 = USDC, token1 = CHECK.
if pa < p < pb:
    L_from_usdc = deposited_usdc * sqrt_p0 * sqrt_pb / (sqrt_pb - sqrt_p0)
    L_from_check = deposited_check / (sqrt_p0 - sqrt_pa)
    L = min(L_from_usdc, L_from_check)
elif p <= pa:
    L = deposited_check / (sqrt_pb - sqrt_pa)
else:
    L = deposited_usdc * sqrt_pa * sqrt_pb / (sqrt_pb - sqrt_pa)

def amounts_for_price(price_check_per_usdc):
    sp = math.sqrt(price_check_per_usdc)

    if price_check_per_usdc <= pa:
        # All token1/CHECK.
        amount0_usdc = 0.0
        amount1_check = L * (sqrt_pb - sqrt_pa)
        status = "OUT_BELOW_RANGE_ALL_CHECK"
    elif price_check_per_usdc >= pb:
        # All token0/USDC.
        amount0_usdc = L * (sqrt_pb - sqrt_pa) / (sqrt_pa * sqrt_pb)
        amount1_check = 0.0
        status = "OUT_ABOVE_RANGE_ALL_USDC"
    else:
        amount0_usdc = L * (sqrt_pb - sp) / (sp * sqrt_pb)
        amount1_check = L * (sp - sqrt_pa)
        status = "IN_RANGE"

    return amount0_usdc, amount1_check, status

amount_usdc, amount_check, range_status = amounts_for_price(p)
position_value_usd = amount_usdc + amount_check * price_usdc_per_check

price_only_pnl_usd = position_value_usd - initial_value_usd
price_only_pnl_pct = price_only_pnl_usd / initial_value_usd * 100.0

hodl_value_usd = deposited_usdc + deposited_check * price_usdc_per_check
lp_vs_hodl_usd = position_value_usd - hodl_value_usd

row = {
    "ts_utc": datetime.now(timezone.utc).isoformat(),
    "tx_hash": env.get("TX_HASH"),
    "position_id": env.get("POSITION_ID"),
    "wallet": env.get("WALLET"),
    "price_usdc_per_check": price_usdc_per_check,
    "price_check_per_usdc": price_check_per_usdc,
    "range_low_check_per_usdc": range_low,
    "range_high_check_per_usdc": range_high,
    "range_status": range_status,
    "estimated_amount_usdc": amount_usdc,
    "estimated_amount_check": amount_check,
    "initial_value_usd": initial_value_usd,
    "estimated_position_value_usd_ex_fees": position_value_usd,
    "price_only_pnl_usd_ex_fees": price_only_pnl_usd,
    "price_only_pnl_pct_ex_fees": price_only_pnl_pct,
    "hodl_value_usd": hodl_value_usd,
    "lp_vs_hodl_usd_ex_fees": lp_vs_hodl_usd,
    "note": "Read-only estimate. Does not include exact unclaimed on-chain fees.",
}

print(json.dumps(row, indent=2))

with open(OUT_DIR / "lp_estimates.jsonl", "a") as f:
    f.write(json.dumps(row) + "\n")
