import requests
import json
import subprocess
import os

# Configuration
API_URL = "https://git.aitosuv.com/api/v1/user/repos"
AUTH = ('admin', 'lsy123123')
REPO_DATA = {
    "name": "gemini-cs",
    "description": "小程序前后台",
    "private": False,
    "auto_init": False
}

def run_command(command):
    """Run a shell command and return the output."""
    print(f"Running: {command}")
    try:
        result = subprocess.run(
            command,
            check=True,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        if result.stdout:
            print(result.stdout.strip())
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"Error running command: {command}")
        print(e.stderr)
        return None

def create_gitignore():
    """Create .gitignore if it doesn't exist."""
    if not os.path.exists(".gitignore"):
        content = """
.venv/
__pycache__/
*.pyc
.trae/
.vscode/
.idea/
*.log
"""
        with open(".gitignore", "w") as f:
            f.write(content.strip())
        print("Created .gitignore")
    else:
        print(".gitignore already exists")

def main():
    clone_url = None
    
    # Initialize session and disable proxy
    session = requests.Session()
    session.trust_env = False
    
    # 1. Create Repository via API
    try:
        response = session.post(API_URL, auth=AUTH, json=REPO_DATA)
        if response.status_code == 201:
            print("Repository created successfully")
            clone_url = response.json()['clone_url']
        elif response.status_code == 422 or response.status_code == 409: # Already exists
            print(f"Repository creation returned {response.status_code}")
            print(f"Response: {response.text}")
            print("Repository already exists")
            # Fetch existing repo details
            user = AUTH[0]
            repo_name = REPO_DATA["name"]
            get_url = f"https://git.aitosuv.com/api/v1/repos/{user}/{repo_name}"
            resp_get = session.get(get_url, auth=AUTH)
            if resp_get.status_code == 200:
                clone_url = resp_get.json()['clone_url']
            else:
                print(f"Could not fetch existing repository details. Status: {resp_get.status_code}")
        else:
            print(f"Failed to create repository: {response.status_code}")
            print(response.text)
            return
    except Exception as e:
        print(f"Error: {e}")
        return

    if not clone_url:
        print("Could not determine clone URL. Exiting.")
        return

    # Embed credentials into the URL for automatic authentication
    # Assuming clone_url format: https://git.aitosuv.com/admin/geminiWX.git
    # We want: https://admin:lsy123123@git.aitosuv.com/admin/geminiWX.git
    if "://" in clone_url:
        protocol, rest = clone_url.split("://", 1)
        auth_url = f"{protocol}://{AUTH[0]}:{AUTH[1]}@{rest}"
    else:
        auth_url = clone_url # Fallback if format is unexpected

    print(f"Target Remote URL: {clone_url}")

    # 2. Local Git Operations
    if not os.path.exists(".git"):
        print("Initializing git repository...")
        run_command("git init")
    
    # Configure git user for this repository
    print("Configuring git user...")
    run_command(f'git config user.email "{AUTH[0]}@aitosuv.com"')
    run_command(f'git config user.name "{AUTH[0]}"')
    
    create_gitignore()
    
    print("Adding files...")
    run_command("git add .")
    
    print("Committing changes...")
    run_command('git commit -m "Initial commit"')
    
    # Check and configure remote
    remotes = run_command("git remote -v")
    if remotes and "origin" in remotes:
        print("Updating remote 'origin'...")
        run_command(f"git remote set-url origin {auth_url}")
    else:
        print("Adding remote 'origin'...")
        run_command(f"git remote add origin {auth_url}")
        
    # Push to remote
    print("Pushing to remote...")
    # Try pushing to master first, then main if that fails (or vice versa depending on default branch)
    # Usually 'master' is default for older git, 'main' for newer.
    # We can try checking current branch name.
    current_branch = run_command("git rev-parse --abbrev-ref HEAD")
    if current_branch:
        if run_command(f"git push -u origin {current_branch} -f") is None:
            print("Push failed.")
    else:
        # Fallback if we couldn't get branch name
        if run_command("git push -u origin master -f") is None:
            run_command("git push -u origin main -f")

if __name__ == "__main__":
    main()
