import sqlite3
from datetime import datetime
from collections import Counter
import json


def fetch_logs() -> list[str]:
    conn = sqlite3.connect("activity_log.db")
    cursor = conn.cursor()
    cursor.execute("SELECT timestamp FROM activity_log")
    logs = [row[0] for row in cursor.fetchall()]
    conn.close()
    return logs


def group_logs_by_day(timestamps: list[str]) -> Counter:
    days = [
        datetime.strptime(ts, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
        for ts in timestamps
    ]
    return Counter(days)


def export_to_json(activity_counts: Counter, output_file: str) -> None:
    data = [
        {
            "date": date,
            "count": count,
        }
        for date, count in activity_counts.items()
    ]
    with open(output_file, "w") as f:
        json.dump(data, f, indent=4)


if __name__ == "__main__":
    logs = fetch_logs()
    if not logs:
        print("No logs found.")
    else:
        activity_counts = group_logs_by_day(logs)
        export_to_json(activity_counts, "activity_data.json")
