import os
import shutil
import tempfile
import subprocess
import random
import string
import argparse
import datetime

def generate_random_string(length: int) -> str:
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

def process_file(file_path: str) -> bool:
    """
    Copies a file to a temporary directory, generates a requirements file 
    using uvx pipreqs, copies the generated requirements back to the original 
    directory (with a timestamped filename), and finally runs the file with 
    'uv run' using that requirements file.
    
    Returns True on success, False otherwise.
    """
    try:
        original_dir = os.path.dirname(os.path.abspath(file_path))
        base_name = os.path.basename(file_path)
        file_name_without_ext = os.path.splitext(base_name)[0]

        # Use a TemporaryDirectory context so it auto-cleans
        with tempfile.TemporaryDirectory() as temp_dir:
            temp_file_path = os.path.join(temp_dir, base_name)
            shutil.copy2(file_path, temp_file_path)

            # Save the current working directory and switch to the temp dir
            previous_cwd = os.getcwd()
            os.chdir(temp_dir)

            # Run uvx pipreqs to generate requirements.txt in the temp directory
            try:
                subprocess.run(
                    ["uvx", "pipreqs", "."],
                    check=True,
                    capture_output=True,
                    text=True
                )
            except subprocess.CalledProcessError as e:
                print("Error running uvx pipreqs:")
                print(e.stderr)
                return False

            # Verify that requirements.txt was generated
            req_path = os.path.join(temp_dir, "requirements.txt")
            if not os.path.exists(req_path):
                print("requirements.txt not found in temporary directory.")
                return False

            # Create a timestamped copy of requirements.txt back in the original directory
            timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            dest_req_filename = f"requirements-{file_name_without_ext}-{timestamp}.txt"
            dest_req_path = os.path.join(original_dir, dest_req_filename)
            shutil.copy2(req_path, dest_req_path)

            # Return to the original directory before running uv
            os.chdir(previous_cwd)

            # Run the file with uv run using the generated requirements file
            try:
                run_result = subprocess.run(
                    ["uv", "run", "--with-requirements", dest_req_path, file_path],
                    capture_output=True,
                    text=True
                )
                if run_result.returncode != 0:
                    print("Error running file with uv run:")
                    print(run_result.stderr)
                    return False
                else:
                    print("Script output:")
                    print(run_result.stdout)
            except Exception as run_err:
                print(f"An error occurred while running uv run: {run_err}")
                return False

        return True  # Temporary directory cleaned up automatically
    except Exception as e:
        print(f"An error occurred while processing the file: {e}")
        return False

def main():
    parser = argparse.ArgumentParser(
        description="Process a file: generate requirements and run it with uv run."
    )
    parser.add_argument("file_path", help="Path to the file to process")
    args = parser.parse_args()

    if process_file(args.file_path):
        print("File processed successfully.")
    else:
        print("File processing failed.")

if __name__ == "__main__":
    main()
