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

def main():
    parser = argparse.ArgumentParser(description="Parses key ProjectSettings files 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')
    # This script doesn't search asset folders, so ignored_folders is not needed,
    # but we add it to prevent unrecognized argument errors.
    parser.add_argument("--ignored-folders", type=str, default='[]')
    args = parser.parse_args()

    input_dir = Path(args.input).resolve()
    output_dir = Path(args.output).resolve()
    project_settings_dir = input_dir / "ProjectSettings"
    output_settings_dir = output_dir / "ProjectSettings"

    if not project_settings_dir.is_dir():
        print("No ProjectSettings directory found.")
        return

    files_to_parse = [
        "TagManager.asset", "DynamicsManager.asset", "Physics2DSettings.asset",
        "EditorBuildSettings.asset", "GraphicsSettings.asset", "QualitySettings.asset",
        "InputManager.asset", "ProjectSettings.asset"
    ]

    print(f"\n--- Starting Project Settings Parsing ---")
    found_any = False

    for filename in files_to_parse:
        file_path = project_settings_dir / filename
        if not file_path.is_file():
            continue

        found_any = True
        print(f"Processing: {filename}")
        
        output_path = (output_settings_dir / filename).with_suffix('.json')
        output_path.parent.mkdir(parents=True, exist_ok=True)

        try:
            documents = load_unity_yaml(file_path)
            if documents:
                # Most settings files have one document, export it directly
                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 {filename}: {e}", file=sys.stderr)

    if not found_any:
        print("No project settings files found to parse.")
    else:
        print("Project settings parsing complete.")

if __name__ == "__main__":
    main()
