"""Phase 4: Release Automation"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_ship.ipynb.

# %% auto 0
__all__ = ['get_version_from_settings', 'ship']

# %% ../nbs/04_ship.ipynb 3
import sys
from pathlib import Path
from .core import run_cmd, hr

# %% ../nbs/04_ship.ipynb 5
def get_version_from_settings():
    """Extract version from settings.ini"""
    settings_path = Path("settings.ini")
    if not settings_path.exists():
        print("❌ Error: settings.ini not found")
        sys.exit(1)
    
    for line in settings_path.read_text().splitlines():
        if line.startswith("version"):
            return line.split("=")[1].strip()
    
    print("❌ Error: version not found in settings.ini")
    sys.exit(1)

# %% ../nbs/04_ship.ipynb 8
def ship(args):
    """Ship a new release: bump version, sync, build, upload, tag, and create GitHub release"""
    
    if args.dry_run:
        print("🏃 DRY RUN MODE - No changes will be made\n")
    
    print(hr * 60)
    print("PHASE 4: SHIP")
    print(hr * 60)
    
    # 0. Check for uncommitted changes
    print("🔍 0. Checking for uncommitted changes")
    status_result = run_cmd(["git", "status", "--porcelain"], capture_output=True, check=False)
    
    if status_result.stdout.strip():
        print("\n❌ Error: You have uncommitted changes!")
        print("   Commit or stash them before shipping")
        if not args.force:
            sys.exit(1)
        else:
            print("   ⚠️  --force specified, continuing anyway...")
    else:
        print("   ✓ Working directory clean")
    
    # 1. Bump version
    print(f"\n📈 1. Bumping version (part {args.part})")
    
    if args.dry_run:
        print("   [DRY RUN] Would run: nbdev_bump_version --part", args.part)
        # Get current version for dry run
        version = get_version_from_settings()
        parts = version.split('.')
        parts[args.part] = str(int(parts[args.part]) + 1)
        new_version = '.'.join(parts)
        print(f"   [DRY RUN] Current: {version} → New: {new_version}")
    else:
        run_cmd(["nbdev_bump_version", "--part", str(args.part)], verbose=args.verbose)
        new_version = get_version_from_settings()
        print(f"   New version: {new_version}")
    
    # 2. Sync the version bump
    print(f"\n🔄 2. Syncing version bump")
    commit_msg = f"Bump version to {new_version}"
    
    if args.dry_run:
        print(f"   [DRY RUN] Would run: git add -A && git commit -m '{commit_msg}' && git push")
    else:
        # TODO: Replace with git_sync(commit_msg, args.verbose) once extracted to core
        run_cmd(["git", "add", "-A"], verbose=args.verbose)
        run_cmd(["git", "commit", "-m", commit_msg], verbose=args.verbose)
        run_cmd(["git", "push"], verbose=args.verbose)
    
    # 3. Build and upload to PyPI
    print(f"\n📦 3. Building and uploading to PyPI")
    
    if args.dry_run:
        print("   [DRY RUN] Would run: nbdev_pypi")
    else:
        if args.skip_pypi:
            print("   ⏭️  Skipped (--skip-pypi)")
        else:
            run_cmd(["nbdev_pypi"], verbose=args.verbose)
            print(f"   ✓ Uploaded to PyPI")
    
    # 4. Tag the release
    print(f"\n🏷️  4. Tagging release v{new_version}")
    tag_name = f"v{new_version}"
    
    if args.dry_run:
        print(f"   [DRY RUN] Would run: git tag -a {tag_name} -m 'Release {tag_name}'")
        print(f"   [DRY RUN] Would run: git push --tags")
    else:
        run_cmd(["git", "tag", "-a", tag_name, "-m", f"Release {tag_name}"], verbose=args.verbose)
        run_cmd(["git", "push", "--tags"], verbose=args.verbose)
        print(f"   ✓ Tagged as {tag_name}")
    
    # 5. Create GitHub release
    print(f"\n🚀 5. Creating GitHub release")
    
    if args.dry_run:
        print(f"   [DRY RUN] Would run: gh release create {tag_name} --generate-notes")
    else:
        if args.skip_gh_release:
            print("   ⏭️  Skipped (--skip-gh-release)")
        else:
            run_cmd(["gh", "release", "create", tag_name, "--generate-notes"], verbose=args.verbose)
            print(f"   ✓ GitHub release created")
    
    # Success!
    print("\n" + hr * 60)
    print(f"✅ Release v{new_version} shipped!")
    print(hr * 60)
    
    if not args.dry_run:
        print(f"\n📍 Links:")
        print(f"   PyPI: https://pypi.org/project/pj-sh/{new_version}/")
        
        # Get repo URL
        repo_result = run_cmd(
            ["gh", "repo", "view", "--json", "url", "--jq", ".url"],
            capture_output=True,
            check=False
        )
        if repo_result.returncode == 0:
            repo_url = repo_result.stdout.strip()
            print(f"   GitHub: {repo_url}/releases/tag/{tag_name}")
        
        print(f"\n💡 Don't forget to:")
        print(f"   uv tool upgrade pj-sh  # Update your global install")
