import json
from datetime import datetime, timedelta
from pathlib import Path
from config import LOG_FILE, EXPIRATION_HOURS

def load_log():
    if Path(LOG_FILE).exists():
        with open(LOG_FILE, "r") as f:
            return json.load(f)
    return {}

def save_log(log):
    with open(LOG_FILE, "w") as f:
        json.dump(log, f, indent=2)

def was_recently_sent(log, cart_id, message_type):
    cid = str(cart_id)
    if cid in log and message_type in log[cid]:
        sent_time = datetime.fromisoformat(log[cid][message_type])
        return datetime.now() - sent_time < timedelta(hours=EXPIRATION_HOURS)
    return False

def update_log(log, cart_id, message_type):
    cid = str(cart_id)
    if cid not in log:
        log[cid] = {}
    log[cid][message_type] = datetime.now().isoformat()
    save_log(log)

def clean_expired_entries(log):
    cutoff = datetime.now() - timedelta(hours=EXPIRATION_HOURS)
    cleaned = {}
    for cid, entries in log.items():
        valid = {
            mtype: ts for mtype, ts in entries.items()
            if datetime.fromisoformat(ts) > cutoff
        }
        if valid:
            cleaned[cid] = valid
    return cleaned
