import argparse
import sys
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
from json_utils import write_json
from yaml_utils import load_unity_yaml, convert_to_plain_python_types

def main():
    parser = argparse.ArgumentParser(description="Parses generic YAML-based assets (.mat, .controller, .anim) into JSON.")
    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.")
    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

    extensions = ['.mat', '.controller', '.anim']
    files_to_process = []
    for ext in extensions:
        files_to_process.extend(find_files_by_extension(str(assets_dir), ext, ignored_folders=ignored_folders, project_root=input_dir))

    if not files_to_process:
        print("No generic asset files (.mat, .controller, .anim) found.")
        return

    print(f"\n--- Starting Generic Asset Parsing ---")
    print(f"Found {len(files_to_process)} files to process.")

    for file_path_str in files_to_process:
        file_path = Path(file_path_str)
        
        relative_path = file_path.relative_to(assets_dir)
        output_path = (output_assets_dir / relative_path).with_suffix('.json')
        output_path.parent.mkdir(parents=True, exist_ok=True)

        try:
            documents = load_unity_yaml(file_path)
            if documents:
                # Most asset files have one document
                data = convert_to_plain_python_types(documents[0])
                write_json(data, output_path, indent=args.indent, shrink=args.shrink_json)
        except Exception as e:
            print(f"Error processing {file_path.name}: {e}", file=sys.stderr)

    print("Generic asset parsing complete.")

if __name__ == "__main__":
    main()
