import subprocess
import logging
from typing import List

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def get_git_log() -> str:
    """
    Executes the `git log` command and returns the output.

    Returns:
        str: The output of the `git log` command.

    Raises:
        CalledProcessError: If the `git log` command fails.
    """
    try:
        result = subprocess.run(['git', 'log', '--pretty=format:%s'], capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        logging.error(f"Error executing git log: {e}")
        raise

def parse_git_log(log_output: str) -> List[str]:
    """
    Parses the git log output into a list of commit messages.

    Args:
        log_output (str): The output of the `git log` command.

    Returns:
        List[str]: A list of commit messages.
    """
    return log_output.strip().split('\n')

def generate_changelog(commits: List[str]) -> str:
    """
    Formats the commit messages into a changelog.

    Args:
        commits (List[str]): A list of commit messages.

    Returns:
        str: The generated changelog.
    """
    changelog = "## Changelog\n\n"
    for commit in commits:
        changelog += f"- {commit}\n"
    return changelog

def write_changelog_to_file(changelog: str, filepath: str) -> None:
    """
    Writes the changelog to a file.

    Args:
        changelog (str): The changelog to write.
        filepath (str): The path to the file to write the changelog to.

    Raises:
        OSError: If there is an error writing to the file.
    """
    try:
        with open(filepath, 'w') as f:
            f.write(changelog)
        logging.info(f"Changelog written to {filepath}")
    except OSError as e:
        logging.error(f"Error writing to file: {e}")
        raise

def main() -> None:
    """
    Main function to generate changelog from git commits and write it to a file.
    """
    try:
        log_output = get_git_log()
        commits = parse_git_log(log_output)
        changelog = generate_changelog(commits)
        write_changelog_to_file(changelog, '/mnt/e/genesis-system/core/docs/changelog.md')  # Changed to .md extension
    except Exception as e:
        logging.error(f"An error occurred: {e}")

if __name__ == "__main__":
    main()