"""
Changelog generator for project documentation.
"""

import os
from datetime import datetime
from typing import List, Dict, Any


def update_changelog_file(
    changelog_entries: List[Dict[str, Any]],
    changelog_file: str,
    max_entries: int = 100,
    verbose: bool = False,
) -> bool:
    """Update the changelog file with new entries."""
    if not changelog_file:
        if verbose:
            print("No changelog file specified, skipping update")
        return False

    if verbose:
        print(f"Updating changelog file: {changelog_file}")
        print(f"Found {len(changelog_entries)} entries to add")

    # Ensure the directory exists if the file is not in the current directory
    changelog_dir = os.path.dirname(changelog_file)
    if (
        changelog_dir
    ):  # Only create directory if there is one (not empty string)
        os.makedirs(changelog_dir, exist_ok=True)

    # Create the file if it doesn't exist
    if not os.path.exists(changelog_file):
        with open(changelog_file, "w", encoding="utf-8") as f:
            f.write("# Changelog\n\n")
        if verbose:
            print(f"Created new changelog file: {changelog_file}")

    # Read existing content
    with open(changelog_file, "r", encoding="utf-8") as f:
        content = f.read()

    # Extract header (everything before the first entry)
    header_end = content.find("## ")
    if header_end == -1:
        header = "# Changelog\n\n"
    else:
        header = content[:header_end]

    # Format new entries
    new_entries = []

    # Group entries by date
    entries_by_date = {}
    for entry in changelog_entries:
        date = entry.get("date", "")
        if not date:
            continue

        if date not in entries_by_date:
            entries_by_date[date] = []

        entries_by_date[date].append(entry)

    # Sort dates in reverse chronological order
    for date in sorted(entries_by_date.keys(), reverse=True):
        entries = entries_by_date[date]

        # Format date as a section header
        new_entries.append(f"## {date}\n")

        # Add each entry
        for entry in entries:
            message = entry.get("message", "").strip()
            commit = entry.get("commit", "")

            if message:
                # Clean up the message
                if message.startswith("- "):
                    message = message[2:]

                new_entries.append(f"- {message} ({commit})")

        new_entries.append("")  # Add an empty line after each date section

    # If no new entries, just return
    if not new_entries:
        if verbose:
            print("No new entries to add to changelog")
        return False

    # Combine header and new entries
    new_content = header + "\n".join(new_entries)

    # Write the updated content
    with open(changelog_file, "w", encoding="utf-8") as f:
        f.write(new_content)

    if verbose:
        print(f"Updated changelog with {len(changelog_entries)} new entries")

    return True
