#! /usr/bin/env python
import argparse
import sys
import logging
import json
import subprocess
import os
from pathlib import Path

logger = logging.getLogger(__name__)


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="basejump fetch", description="Fetches all changes for a whole codebase"
    )
    ap.add_argument("name", help="The name of the codebase")
    ap.add_argument("--pull", help="Perform a full pull", action="store_true")
    ap.add_argument(
        "-v", "--verbose", help="Enable verbose logging", action="store_true"
    )
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(levelname)s:	%(message)s",
    )

    # Ensure that the basejump config dir exists
    bj_config_dir = Path.home() / ".config" / "basejump"
    bj_config_dir.mkdir(parents=True, exist_ok=True)

    # Read the codebase config
    codebase_config_path = bj_config_dir / f"{args.name}.codebase.json"
    if not codebase_config_path.exists():
        logger.error(f"Codebase `{args.name}` does not exist")
        return 1
    config = json.loads(codebase_config_path.read_text())

    # Handle each repository
    for repo in config["repos"]:
        logger.info(f"Fetching {repo['path']}")
        
        # If we are in pull mode, do a git pull
        if args.pull:
            subprocess.run(["git", "pull"], cwd=repo["path"])

        # Otherwise fetch all
        else:
            subprocess.run(["git", "fetch", "--all"], cwd=repo["path"])

    return 0


if __name__ == "__main__":
    sys.exit(main())