#!/bin/bash
# Update agent commit hashes for current project
# Usage: update-agent-hashes [claude|opencode]
# Default: claude

TARGET=${1:-claude}
PROJECT_ROOT=$(pwd)

if [[ "$TARGET" == "claude" ]]; then
  CONFIG_DIR="$PROJECT_ROOT/.claude"
  AGENTS_DIR="agents"
  AGENT_MAPPING="$CONFIG_DIR/agent-hashes.json"
elif [[ "$TARGET" == "opencode" ]]; then
  CONFIG_DIR="$PROJECT_ROOT/.opencode"
  AGENTS_DIR="agent"
  AGENT_MAPPING="$CONFIG_DIR/agent-hashes.json"
else
  echo "Error: Invalid target '$TARGET'. Use 'claude' or 'opencode'"
  exit 1
fi

# Check if we're in a project with target directory
if [[ ! -d "$CONFIG_DIR" ]]; then
  echo "Error: Not in a project with $CONFIG_DIR directory"
  exit 1
fi

echo "Updating agent hashes for $TARGET in project: $(basename "$PROJECT_ROOT")"

# Create agent hash mapping using Python
python3 -c "
import json
import subprocess
import os
from pathlib import Path
from datetime import datetime, timezone

def get_agent_hash(agent_file, repo_path):
    try:
        result = subprocess.run(['git', 'log', '--oneline', '-1', '--', agent_file], 
                              cwd=repo_path, capture_output=True, text=True)
        if result.returncode == 0 and result.stdout.strip():
            return result.stdout.strip().split()[0]
    except Exception as e:
        print(f'Warning: Could not get hash for {agent_file}: {e}')
    return 'unknown'

agents = {}
project_root = '$PROJECT_ROOT'

# Check global agents
target = '$TARGET'
if target == 'claude':
    global_agents_path = os.path.expanduser('~/.claude/agents')
    agents_dir = 'agents'
elif target == 'opencode':
    global_agents_path = os.path.expanduser('~/.config/opencode/agent')
    agents_dir = 'agent'

if os.path.exists(global_agents_path):
    print(f'Scanning global {target} agents...')
    for agent_file in Path(global_agents_path).glob('*.md'):
        agent_name = agent_file.stem
        hash_val = get_agent_hash(agent_file.name, global_agents_path)
        agents[agent_name] = {'hash': hash_val, 'source': 'global'}

# Check project agents (override global if present)
project_agents_path = f'{project_root}/.{target}/{agents_dir}'
if os.path.exists(project_agents_path):
    print(f'Scanning project {target} agents...')
    for agent_file in Path(project_agents_path).glob('*.md'):
        agent_name = agent_file.stem  
        hash_val = get_agent_hash(agent_file.name, project_agents_path)
        agents[agent_name] = {'hash': hash_val, 'source': 'project'}

# Create final mapping
mapping = {
    '_metadata': {
      'updated': datetime.now(timezone.utc).isoformat() + 'Z',
        'project': os.path.basename(project_root)
    },
    'agents': agents
}

with open('$AGENT_MAPPING', 'w') as f:
    json.dump(mapping, f, indent=2)

print(f'Updated {len(agents)} agent hashes in .claude/agent-hashes.json')
"

if [ $? -eq 0 ]; then
  echo "✅ Agent hashes updated successfully"
else
  echo "❌ Failed to update agent hashes"
  exit 1
fi
