import json
import os
from datetime import datetime

LOG_DIR = "logs"

def get_daily_log_file():
    """יוצר שם קובץ לוג לפי התאריך של היום"""
    if not os.path.exists(LOG_DIR):
        os.makedirs(LOG_DIR)
    
    today = datetime.now().strftime("%Y-%m-%d")
    return os.path.join(LOG_DIR, f"bot_log_{today}.json")


def append_log(record):
    """שומר רשומה ללוג היומי"""
    log_file = get_daily_log_file()
    
    # הוסף timestamp בפורמט קריא
    record['timestamp_readable'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    if not os.path.exists(log_file):
        with open(log_file, "w", encoding="utf8") as f:
            json.dump([record], f, indent=2)
        return

    try:
        with open(log_file, "r", encoding="utf8") as f:
            data = json.load(f)
    except:
        data = []

    data.append(record)

    with open(log_file, "w", encoding="utf8") as f:
        json.dump(data, f, indent=2)


def cleanup_old_logs(days_to_keep=30):
    """מוחק לוגים ישנים (אופציונלי)"""
    if not os.path.exists(LOG_DIR):
        return
    
    now = datetime.now()
    for filename in os.listdir(LOG_DIR):
        if filename.startswith("bot_log_") and filename.endswith(".json"):
            filepath = os.path.join(LOG_DIR, filename)
            file_time = datetime.fromtimestamp(os.path.getmtime(filepath))
            
            # מחק קבצים ישנים מדי
            if (now - file_time).days > days_to_keep:
                try:
                    os.remove(filepath)
                    print(f"🗑️ Deleted old log: {filename}")
                except Exception as e:
                    print(f"Error deleting {filename}: {e}")
