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 shader files (.shader, .shadergraph) 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

    shader_files = find_files_by_extension(str(assets_dir), '.shader', ignored_folders=ignored_folders, project_root=input_dir)
    shader_graph_files = find_files_by_extension(str(assets_dir), '.shadergraph', ignored_folders=ignored_folders, project_root=input_dir)
    files_to_copy = shader_files + shader_graph_files

    if not files_to_copy:
        print("No shader files found to copy.")
        return

    print(f"\n--- Starting Shader Handling ---")
    print(f"Found {len(files_to_copy)} shader files to copy.")

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

if __name__ == "__main__":
    main()
