#!/usr/bin/env python3
import sys
import subprocess

# === AUTO INSTALL ===
def ensure(pkg):
    try:
        __import__(pkg)
    except ImportError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])

ensure("pandas")
ensure("matplotlib")

import pandas as pd
import matplotlib.pyplot as plt

# === ARGS ===
if len(sys.argv) < 2:
    print("Usage: python graph.py data.csv")
    sys.exit(1)

FILE = sys.argv[1]

# === LOAD ===
df = pd.read_csv(FILE)

if "datetime" not in df.columns:
    print("Missing datetime column")
    sys.exit(1)

df["datetime"] = pd.to_datetime(df["datetime"])
df = df.sort_values("datetime")

# === CHECK REQUIRED COLS ===
required = ["profit", "buy_in", "category"]
for col in required:
    if col not in df.columns:
        print(f"Missing column: {col}")
        sys.exit(1)

# === 1. CUMULATIVE PROFIT ===
df["cum_profit"] = df["profit"].cumsum()

plt.figure()
plt.plot(df["datetime"], df["cum_profit"])
plt.title("Cumulative Profit")
plt.xlabel("Time")
plt.ylabel("€")
plt.xticks(rotation=45)
plt.tight_layout()

# === 2. PROFIT PER GAME (SCATTER) ===
plt.figure()
plt.scatter(range(len(df)), df["profit"])
plt.title("Profit per Game")
plt.xlabel("Game #")
plt.ylabel("€")
plt.tight_layout()

# === 3. ROI BY CATEGORY ===
roi = df.groupby("category").apply(
    lambda x: x["profit"].sum() / x["buy_in"].sum()
)

plt.figure()
roi.plot(kind="bar")
plt.title("ROI by Game Type")
plt.xlabel("Category")
plt.ylabel("ROI")
plt.tight_layout()

# === 4. SESSION PERFORMANCE ===
if "session" in df.columns:
    session_profit = df.groupby("session")["profit"].sum()

    plt.figure()
    session_profit.plot(kind="bar")
    plt.title("Profit by Session")
    plt.xlabel("Session")
    plt.ylabel("€")
    plt.tight_layout()

# === 5. WIN DISTRIBUTION ===
if "position" in df.columns:
    pos_counts = df["position"].value_counts()

    plt.figure()
    pos_counts.plot(kind="bar")
    plt.title("Position Distribution")
    plt.xlabel("Position")
    plt.ylabel("Count")
    plt.tight_layout()

# === SHOW ALL ===
plt.show()
