#!/usr/bin/env python3
"""
Fix JSON output structure in processor scripts to include processor_name field.
"""

import os
import re
import sys


def fix_face_processor():
    """Fix Face processor JSON output."""
    filepath = "scripts/face_processor_contract_v1.py"

    with open(filepath, "r") as f:
        content = f.read()

    # Fix success return (line ~446)
    success_pattern = r'(\s+)return \{\s*"status": "success",'
    success_replacement = r'\1return {\n\1    "processor_name": PROCESSOR_NAME,\n\1    "processor_version": PROCESSOR_VERSION,\n\1    "contract_version": CONTRACT_VERSION,\n\1    "status": "success",'

    content = re.sub(success_pattern, success_replacement, content, flags=re.DOTALL)

    # Fix error returns
    error_pattern = r'(\s+)return \{\s*"status": "error",'
    error_replacement = r'\1return {\n\1    "processor_name": PROCESSOR_NAME,\n\1    "processor_version": PROCESSOR_VERSION,\n\1    "contract_version": CONTRACT_VERSION,\n\1    "status": "error",'

    content = re.sub(error_pattern, error_replacement, content, flags=re.DOTALL)

    # Remove duplicate processor_version and contract_version fields
    # after we've already added them at the beginning
    content = re.sub(
        r'"processor_version": PROCESSOR_VERSION,.*\n.*"contract_version": CONTRACT_VERSION,',
        "",
        content,
        flags=re.DOTALL,
    )

    with open(filepath, "w") as f:
        f.write(content)

    print(f"Fixed {filepath}")


def fix_pose_processor():
    """Fix Pose processor JSON output."""
    filepath = "scripts/pose_processor_contract_v1.py"

    with open(filepath, "r") as f:
        content = f.read()

    # Fix success return
    success_pattern = r'(\s+)return \{\s*"status": "success",'
    success_replacement = r'\1return {\n\1    "processor_name": PROCESSOR_NAME,\n\1    "processor_version": PROCESSOR_VERSION,\n\1    "contract_version": CONTRACT_VERSION,\n\1    "status": "success",'

    content = re.sub(success_pattern, success_replacement, content, flags=re.DOTALL)

    # Fix error returns
    error_pattern = r'(\s+)return \{\s*"status": "error",'
    error_replacement = r'\1return {\n\1    "processor_name": PROCESSOR_NAME,\n\1    "processor_version": PROCESSOR_VERSION,\n\1    "contract_version": CONTRACT_VERSION,\n\1    "status": "error",'

    content = re.sub(error_pattern, error_replacement, content, flags=re.DOTALL)

    # Remove duplicate processor_version and contract_version fields
    content = re.sub(
        r'"processor_version": PROCESSOR_VERSION,.*\n.*"contract_version": CONTRACT_VERSION,',
        "",
        content,
        flags=re.DOTALL,
    )

    with open(filepath, "w") as f:
        f.write(content)

    print(f"Fixed {filepath}")


def main():
    """Main function."""
    print("Fixing processor JSON output structure...")

    fix_face_processor()
    fix_pose_processor()

    print("\nDone! Run verification again to check compliance.")


if __name__ == "__main__":
    main()
