#!/usr/bin/env python3
"""
Script to verify that the 'bots' field in data/botPolicies.yaml
has the same semantic contents as data/meta/default-config.yaml.

CW: generated by AI
"""

import yaml
import sys
import os
import subprocess
import difflib

def load_yaml(file_path):
    """Load YAML file and return the data."""
    try:
        with open(file_path, 'r') as f:
            return yaml.safe_load(f)
    except Exception as e:
        print(f"Error loading {file_path}: {e}")
        sys.exit(1)

def normalize_yaml(data):
    """Normalize YAML data by removing comments and standardizing structure."""
    # For lists, just return as is, since YAML comments are stripped by safe_load
    return data

def get_repo_root():
    """Get the root directory of the git repository."""
    try:
        result = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True, text=True, check=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError:
        print("Error: Not in a git repository")
        sys.exit(1)

def main():
    # Get the git repository root
    repo_root = get_repo_root()

    # Paths relative to the repo root
    bot_policies_path = os.path.join(repo_root, 'data', 'botPolicies.yaml')
    default_config_path = os.path.join(repo_root, 'data', 'meta', 'default-config.yaml')

    # Load the files
    bot_policies = load_yaml(bot_policies_path)
    default_config = load_yaml(default_config_path)

    # Extract the 'bots' field from botPolicies.yaml
    if 'bots' not in bot_policies:
        print("Error: 'bots' field not found in botPolicies.yaml")
        sys.exit(1)
    bots_field = bot_policies['bots']

    # The default-config.yaml is a list directly
    default_bots = default_config

    # Normalize both
    normalized_bots = normalize_yaml(bots_field)
    normalized_default = normalize_yaml(default_bots)

    # Compare
    if normalized_bots == normalized_default:
        print("SUCCESS: The 'bots' field in botPolicies.yaml matches the contents of default-config.yaml")
        sys.exit(0)
    else:
        print("FAILURE: The 'bots' field in botPolicies.yaml does not match the contents of default-config.yaml")
        print("\nDiff:")
        bots_yaml = yaml.dump(normalized_bots, default_flow_style=False)
        default_yaml = yaml.dump(normalized_default, default_flow_style=False)
        diff = difflib.unified_diff(
            bots_yaml.splitlines(keepends=True),
            default_yaml.splitlines(keepends=True),
            fromfile='bots field in botPolicies.yaml',
            tofile='default-config.yaml'
        )
        print(''.join(diff))
        sys.exit(1)

if __name__ == "__main__":
    main()