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

logger = logging.getLogger(__name__)


def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="basejump discover", description="Discover repos in a codebase"
    )
    ap.add_argument("root_path", help="The root path of the codebase", type=Path)
    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",
    )
    
    # Find all git repos in the codebase
    logger.info(f"Searching for git repos in: {args.root_path}")
    repos = []
    for path in args.root_path.rglob(".git"):
        repos.append({"path":str(path.parent.absolute())})
        
    # For each repo, find the upstream 
    logger.info("Finding upstream URLs...")
    for repo in repos:
        # Get the upstream URL
        upstream_url = subprocess.run(
            ["git", "remote", "get-url", "origin"],
            cwd=repo["path"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding="utf-8",
        ).stdout.strip()
        
        # Add the upstream URL to the repo config
        repo["upstream"] = upstream_url
        
    # Print the results
    logger.info("Found the following repos:")
    print(json.dumps(repos, indent=4))

    return 0


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