#!/usr/bin/env python3
import os
import subprocess


def determine_version_bump_type(fragment_dir: str) -> str:
    files = os.listdir(fragment_dir)

    has_breaking = any(f.endswith(".major.md") for f in files)
    has_feature = any(f.endswith(".minor.md") for f in files)

    if has_breaking:
        return "major"
    elif has_feature:
        return "minor"
    else:
        return "patch"


current_dir = os.getcwd()
print(f"Current directory: {current_dir}")

# Get the directory where this script is located
script_dir = os.path.dirname(os.path.abspath(__file__))
# The unreleased_changes directory is at the peer level of the script
news_dir = os.path.join(script_dir, "unreleased_changes")

print(f"Looking for unreleased_changes at: {news_dir}")

# Determine which part to bump
if not os.path.isdir(news_dir):
    raise FileNotFoundError(
        f"Cannot determine version bump: unreleased_changes directory not found at {news_dir}"
    )
bump_type = determine_version_bump_type(news_dir)
print(f"Determined bump type: {bump_type}")

try:
    new_version = next(
        (
            line.split("=")[1]
            for line in subprocess.run(
                ["bump2version", bump_type, "--dry-run", "--list"],
                capture_output=True,
                text=True,
                check=True,
            ).stdout.splitlines()
            if line.startswith("new_version=")
        ),
        None,
    )
except subprocess.CalledProcessError as e:
    print(f"Error running bump2version: {e.stderr}")
    raise

if not new_version:
    raise ValueError("Failed to determine new version from bump2version output")

print(f"New version determined: {new_version}")

subprocess.run(["towncrier", "build", "--version", new_version, "--yes"], check=True)

# --allow-dirty is needed since towncrier updated the change log
subprocess.run(["bump2version", "--allow-dirty", bump_type], check=True)
