import pandas as pd
from pathlib import Path
from datetime import datetime

MTM_FILE = Path("storage/mtm_ledger.csv")

def log_mtm(
    sp_units,
    gd_units,
    sp_price,
    gd_price,
    total_invested,
):
    sp_value = sp_units * sp_price
    gd_value = gd_units * gd_price
    portfolio_value = sp_value + gd_value
    pnl = portfolio_value - total_invested

    row = {
        "timestamp": datetime.utcnow().isoformat(),
        "sp_units": sp_units,
        "gd_units": gd_units,
        "sp_price": sp_price,
        "gd_price": gd_price,
        "sp_value": sp_value,
        "gd_value": gd_value,
        "portfolio_value": portfolio_value,
        "total_invested": total_invested,
        "pnl": pnl,
    }

    df = pd.DataFrame([row])

    MTM_FILE.parent.mkdir(exist_ok=True)

    if MTM_FILE.exists():
        df.to_csv(MTM_FILE, mode="a", header=False, index=False)
    else:
        df.to_csv(MTM_FILE, index=False)

    return portfolio_value, pnl

def should_log_mtm(df, current_ts):
    if df.empty:
        return True
    last_ts = pd.to_datetime(df.iloc[-1]["timestamp"])
    return current_ts.minute != last_ts.minute
