import json
import os
from datetime import date

HISTORY_FILE = "cost_history.json"


def save_cost_snapshot(cost):

    history = []

    if os.path.exists(HISTORY_FILE):
        with open(HISTORY_FILE) as f:
            history = json.load(f)

        # prevent duplicate entries
        if history and history[-1]["cost"] == round(cost, 2):
            return

    history.append({
        "date": str(date.today()),
        "cost": round(cost, 2)
    })

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


def show_cost_trend():

    if not os.path.exists(HISTORY_FILE):
        print("\nNo cost history available.")
        return

    with open(HISTORY_FILE) as f:
        history = json.load(f)

    print("\nInfrastructure Cost Trend")
    print("─" * 30)

    for entry in history:
        print(f"{entry['date']:12} ${entry['cost']:>8.2f}")