import json
import os
from datetime import datetime

HISTORY="/home/lastchar/lastcharter_control_center/data/system_history.json"
AUDIT="/home/lastchar/lastcharter_control_center/data/audit.log"


def save_history(item):

    try:

        data=[]

        if os.path.exists(HISTORY) and os.path.getsize(HISTORY)>0:
            try:
                with open(HISTORY,"r",encoding="utf-8") as f:
                    data=json.load(f)
            except:
                data=[]

        data.append(item)

        data=data[-60:]

        with open(HISTORY,"w",encoding="utf-8") as f:
            json.dump(
                data,
                f,
                indent=2,
                ensure_ascii=False
            )

    except Exception as e:
        with open(
            "/home/lastchar/lastcharter_control_center/data/history_error.log",
            "a"
        ) as f:
            f.write(
                f"{datetime.now()} {e}\n"
            )


def audit(action):

    with open(AUDIT,"a",encoding="utf-8") as f:
        f.write(
            f"{datetime.now()} {action}\n"
        )
