#!/usr/bin/env python3
"""
Automation script to update .claude/settings.local.json with all shell script path variations.

This script:
1. Finds all shell scripts (.sh files) under tools/
2. Finds all CMass* directories in /Volumes/Ephemeral/
3. Generates all path variations for each script:
   - tools/some/script.sh
   - ./tools/some/script.sh
   - /Volumes/Common/QJoon/llm/wdmaker/tools/some/script.sh
   - /Volumes/Ephemeral/CMass*/tools/some/script.sh
4. Updates the allow list in .claude/settings.local.json
5. Removes duplicates and sorts the list
"""

import json
import pathlib
import subprocess
from typing import Set

def find_shell_scripts(tools_dir: pathlib.Path) -> Set[str]:
    """Find all .sh files under tools directory, return relative paths from tools/"""
    scripts = set()
    for sh_file in tools_dir.rglob("*.sh"):
        # Get path relative to tools directory
        rel_path = sh_file.relative_to(tools_dir)
        scripts.add(str(rel_path))
    return scripts

def find_cmass_dirs() -> Set[str]:
    """Find all CMass* directories in /Volumes/Ephemeral/"""
    cmass_dirs = set()
    ephemeral_path = pathlib.Path("/Volumes/Ephemeral")

    if ephemeral_path.exists():
        for item in ephemeral_path.iterdir():
            if item.is_dir() and item.name.startswith("CMass"):
                cmass_dirs.add(item.name)

    return cmass_dirs

def generate_path_variations(script_rel_path: str, cmass_dirs: Set[str]) -> Set[str]:
    """Generate all 4 path variations for a given script"""
    variations = set()

    # Format 1: tools/some/script.sh
    variations.add(f"Bash(tools/{script_rel_path}:*)")

    # Format 2: ./tools/some/script.sh
    variations.add(f"Bash(./tools/{script_rel_path}:*)")

    # Format 3: /Volumes/Common/QJoon/llm/wdmaker/tools/some/script.sh
    variations.add(f"Bash(/Volumes/Common/QJoon/llm/wdmaker/tools/{script_rel_path}:*)")

    # Format 4: /Volumes/Ephemeral/CMass*/tools/some/script.sh
    for cmass_dir in sorted(cmass_dirs):
        variations.add(f"Bash(/Volumes/Ephemeral/{cmass_dir}/tools/{script_rel_path}:*)")

    return variations

def main():
    """Main function to update the settings file"""
    # Get root directory
    script_path = pathlib.Path(__file__).parent.parent
    settings_file = script_path / ".claude" / "settings.local.json"
    tools_dir = script_path / "tools"

    print(f"Root directory: {script_path}")
    print(f"Settings file: {settings_file}")
    print(f"Tools directory: {tools_dir}")
    print()

    # Find all shell scripts
    print("Finding shell scripts...")
    shell_scripts = find_shell_scripts(tools_dir)
    print(f"Found {len(shell_scripts)} shell scripts")
    for script in sorted(shell_scripts)[:5]:
        print(f"  - {script}")
    if len(shell_scripts) > 5:
        print(f"  ... and {len(shell_scripts) - 5} more")
    print()

    # Find all CMass directories
    print("Finding CMass* directories...")
    cmass_dirs = find_cmass_dirs()
    print(f"Found {len(cmass_dirs)} CMass directories:")
    for cmass_dir in sorted(cmass_dirs):
        print(f"  - {cmass_dir}")
    print()

    # Generate all path variations
    print("Generating path variations...")
    all_bash_entries = set()
    for script in shell_scripts:
        variations = generate_path_variations(script, cmass_dirs)
        all_bash_entries.update(variations)
    print(f"Generated {len(all_bash_entries)} total Bash entries")
    print()

    # Read current settings file
    print("Reading settings file...")
    if not settings_file.exists():
        print(f"Error: Settings file not found at {settings_file}")
        return 1

    with open(settings_file, 'r') as f:
        settings = json.load(f)

    # Get current allow list
    current_allow = set(settings.get("permissions", {}).get("allow", []))
    print(f"Current allow list has {len(current_allow)} entries")

    # Extract non-Bash entries
    non_bash_entries = [entry for entry in current_allow if not entry.startswith("Bash(")]
    print(f"Non-Bash entries: {len(non_bash_entries)}")

    # Combine: keep non-Bash entries, merge all Bash entries
    merged_bash_entries = all_bash_entries
    all_entries = non_bash_entries + list(merged_bash_entries)

    print(f"Merged allow list: {len(all_entries)} entries")
    print(f"  Bash entries: {len(merged_bash_entries)}")
    print(f"  Other entries: {len(non_bash_entries)}")
    print()

    # Sort the allow list
    print("Sorting allow list...")
    sorted_allow = sorted(all_entries)

    # Update settings
    settings["permissions"]["allow"] = sorted_allow

    # Write back to file
    print("Writing settings file...")
    with open(settings_file, 'w') as f:
        json.dump(settings, f, indent=2)

    print(f"✓ Successfully updated {settings_file}")
    print()
    print(f"Summary:")
    print(f"  Total entries in allow list: {len(sorted_allow)}")
    print(f"  Bash script entries: {len(merged_bash_entries)}")
    print(f"  Other entries: {len(non_bash_entries)}")

    return 0

if __name__ == "__main__":
    exit(main())
