# time_logger.py
import csv
import os
from datetime import datetime
import logging

logger = logging.getLogger("logger")

_initialized = False
LOG_PATH = os.path.join(os.path.dirname(__file__), "data", "activity_log.csv")


def ensure_log_file():
    """Create the CSV file if it doesn't exist, including headers."""
    os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
    if not os.path.exists(LOG_PATH):
        with open(LOG_PATH, "w", newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(["timestamp", "user_id", "username", "channel_id", "hour", "weekday"])
        logger.info("🗂️ Created new activity_log.csv file.")


def log_message_activity(message):
    """Log basic time and user info for server heatmap analysis."""
    global _initialized
    if not _initialized:
        ensure_log_file()
        _initialized = True

    ts = datetime.now()
    row = [
        ts.strftime("%Y-%m-%d %H:%M:%S"),
        str(message.author.id),
        message.author.display_name,
        str(message.channel.id),
        ts.hour,
        ts.strftime("%A")
    ]

    try:
        with open(LOG_PATH, "a", newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow(row)
        logger.info(f"📝 Logged activity: {message.author.display_name} at {ts.hour}:00 ({ts.strftime('%A')})")
    except Exception as e:
        logger.error(f"❌ Failed to log activity: {e}")
