#! /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 init", description="Creates a new basejump codebase"
    )
    ap.add_argument("name", help="The name of the codebase")
    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)

    # Create a new codebase definition
    codebase_config_path = bj_config_dir / f"{args.name}.codebase.json"

    # If the path already exists, abort
    if codebase_config_path.exists():
        logger.error(f"Codebase `{args.name}` already exists")
        logger.info(f"Config file at: {codebase_config_path}")
        return 1

    # Create a template codebase config
    template_config = {
        "name": args.name,
        "repos": [
            {
                "path": "/tmp/example",
                "upstream": "https://github.com/octocat/Hello-World",
            }
        ],
    }

    # Write the template config to disk
    codebase_config_path.write_text(json.dumps(template_config, indent=4))

    # Open $EDITOR (or vim) to edit the config
    subprocess.run([os.environ.get("EDITOR", "vim"), str(codebase_config_path)])
    
    # Iterate through every repo and clone it
    config = json.loads(codebase_config_path.read_text())
    for repo in config["repos"]:
        if Path(repo["path"]).exists():
            logger.info(f"Skipping {repo['path']}, already exists")
            continue
        
        # Do a clone
        logger.info(f"Cloning {repo['upstream']} into {repo['path']}")
        subprocess.run(["git", "clone", repo["upstream"], repo["path"]])

    return 0


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