import argparse
import sys
import shutil
import json
from pathlib import Path

# Add the utils directory to the Python path
utils_path = Path(__file__).parent.parent / 'utils'
sys.path.append(str(utils_path))

from file_utils import find_files_by_extension

def main():
    parser = argparse.ArgumentParser(description="Copies all C# scripts (.cs) to the target directory.")
    parser.add_argument("--input", type=str, required=True, help="The root directory of the target Unity project.")
    parser.add_argument("--output", type=str, required=True, help="The directory where the output will be saved.")
    # Add arguments that are passed by the orchestrator but not used by this script
    parser.add_argument("--indent", type=int, default=None)
    parser.add_argument("--shrink-json", action='store_true')
    parser.add_argument("--ignored-folders", type=str, default='[]', help='JSON string of folders to ignore.')
    args = parser.parse_args()

    try:
        ignored_folders = json.loads(args.ignored_folders)
    except json.JSONDecodeError:
        print("Warning: Could not parse ignored-folders JSON string. Defaulting to empty list.", file=sys.stderr)
        ignored_folders = []

    input_dir = Path(args.input).resolve()
    output_dir = Path(args.output).resolve()
    assets_dir = input_dir / "Assets"
    output_assets_dir = output_dir / "Assets"

    if not assets_dir.is_dir():
        return

    cs_files = find_files_by_extension(str(assets_dir), '.cs', ignored_folders=ignored_folders, project_root=input_dir)
    if not cs_files:
        print("No C# scripts found to copy.")
        return

    print(f"\n--- Starting Script Handling ---")
    print(f"Found {len(cs_files)} C# script files to copy.")

    for script_path_str in cs_files:
        script_path = Path(script_path_str)
        relative_path = script_path.relative_to(assets_dir)
        destination_path = output_assets_dir / relative_path
        
        destination_path.parent.mkdir(parents=True, exist_ok=True)
        
        try:
            shutil.copy(script_path, destination_path)
        except IOError as e:
            print(f"Error copying {script_path} to {destination_path}: {e}", file=sys.stderr)
    
    print("Script copying complete.")

if __name__ == "__main__":
    main()
