import os
import subprocess
import argparse
import tempfile
from pathlib import Path


def clone_repo(git_url, clone_path):
    """Clone a git repository to the specified path."""
    subprocess.run(["git", "clone", git_url, clone_path], check=True)


def concatenate_files(repo_path, output_file, extensions, repo_title):
    """Concatenate files with specified extensions into a single output file."""
    with open(output_file, "w", encoding="utf-8") as outfile:
        for root, _, files in os.walk(repo_path):
            for file in files:
                if any(file.endswith(ext) for ext in extensions):
                    file_path = os.path.join(root, file)
                    try:
                        with open(file_path, "r", encoding="utf-8") as infile:
                            contents = infile.read()
                            relative_path = file_path.replace(repo_path, repo_title)
                            outfile.write(f"--- {relative_path} ---\n{contents}\n\n")
                    except UnicodeDecodeError:
                        print(f"Skipping non-text file: {file_path}")


def parse_github_url(git_url):
    """Extract username and repository name from a GitHub URL."""
    parts = git_url.split('/')
    repo_name = parts[-1].split('.')[0] if parts[-1].endswith('.git') else parts[-1]
    github_username = parts[-2].split(':')[-1]
    return github_username, repo_name


def main():
    parser = argparse.ArgumentParser(description='Clone a GitHub repo and concatenate files into a single file.')
    parser.add_argument('--git_url', help='GitHub repository URL', default=None)
    parser.add_argument('--dir', help='Directory path to process', default=None)
    parser.add_argument('--extensions', nargs='+', default=['.py'], 
                        help='List of file extensions to include (default: .py)')
    parser.add_argument('--output_dir', help='Output directory', default=None)

    args = parser.parse_args()

    if not (args.git_url or args.dir):
        print("Error: Neither git_url nor dir is provided")
        return

    # Process extensions to ensure they start with a dot
    extensions = [ext if ext.startswith('.') else f'.{ext}' for ext in args.extensions]
    output_dir = args.output_dir if args.output_dir else os.getcwd()
    
    if args.git_url:
        github_username, repo_name = parse_github_url(args.git_url)
        repo_title = f"{github_username}/{repo_name}"
        output_filename = f"{github_username}__{repo_name}.txt"
        
        with tempfile.TemporaryDirectory(dir="/tmp") as directory:
            clone_repo(args.git_url, directory)
            output_path = os.path.join(output_dir, output_filename)
            concatenate_files(directory, output_path, extensions, repo_title)
    else:
        directory = args.dir
        repo_title = args.dir
        output_filename = f"{Path(args.dir).name}.txt"
        output_path = os.path.join(output_dir, output_filename)
        concatenate_files(directory, output_path, extensions, repo_title)

    print(f"Output saved to {output_path}")


if __name__ == "__main__":
    main()
