"""Phase 3: Project Synchronization"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_sync.ipynb.

# %% auto 0
__all__ = ['sync']

# %% ../nbs/03_sync.ipynb 3
import sys
from .core import run_cmd, hr

# %% ../nbs/03_sync.ipynb 6
def sync(args):
    """Sync project: pull, prepare (export/test/clean), commit, and push"""
    print(hr * 60)
    print("PHASE 3: SYNC")
    
    # 1. Git pull
    print("⬇️ 1. Pulling latest changes")
    result = run_cmd(["git", "pull"], check=False, verbose=args.verbose)
    
    if result.returncode != 0:
        status_result = run_cmd(["git", "status", "--porcelain"], capture_output=True, check=False)
        if "UU" in status_result.stdout or "AA" in status_result.stdout:
            print("\n❌ Merge conflict detected!")
            print("   Resolve conflicts manually, then run 'pj sync' again")
            sys.exit(1)
        else:
            print("\n❌ Git pull failed!")
            print("   Fix the issue manually, then try again")
            sys.exit(1)
    
    # 2. nbdev_prepare
    print("🔧 2. Running nbdev_prepare (export, test, clean)")
    prepare_result = run_cmd(["nbdev_prepare"], check=False, capture_output=True)
    
    if prepare_result.returncode != 0:
        print("\n❌ nbdev_prepare failed!")
        print("\nOutput:")
        print(prepare_result.stdout)
        if prepare_result.stderr:
            print("\nErrors:")
            print(prepare_result.stderr)
        print("\n   Fix the errors and try again")
        sys.exit(1)
    
    if args.verbose:
        print(prepare_result.stdout)
    
    # 3. Git commit
    commit_message = args.message or "save"
    print(f"💾 3. Committing changes: '{commit_message}'")
    
    status_result = run_cmd(["git", "status", "--porcelain"], capture_output=True)
    if not status_result.stdout.strip():
        print("   No changes to commit")
    else:
        # TODO: Replace these three lines with git_sync(commit_message, args.verbose)
        run_cmd(["git", "add", "-A"], verbose=args.verbose)
        run_cmd(["git", "commit", "-m", commit_message], verbose=args.verbose)
    
    # 4. Git push
    print("📤 4. Pushing to GitHub")
    run_cmd(["git", "push"], verbose=args.verbose)
    
    print()
    print(hr * 60)
    print("✅ Sync complete!")
