#!/usr/bin/env python3
"""
Script to update agents to use automation-tracking-manager
"""

import re
import os

# Agent configurations
agents = {
    "architecture-guard.md": {
        "prefix": "AUTO-GUARD",
        "tracking_type": "Code Analysis Report",
        "cleanup_func": "cleanup_previous_guard_tracking",
        "create_func": "create_guard_tracking_issue",
    },
    "bug-hunter.md": {
        "prefix": "AUTO-BUG-POOL",
        "tracking_type": "Bug Detection Report",
        "cleanup_func": "cleanup_previous_bug_hunter_tracking",
        "create_func": "create_bug_hunter_tracking_issue",
    },
    "docs-writer.md": {
        "prefix": "AUTO-DOCS",
        "tracking_type": "Documentation Report",
        "cleanup_func": "cleanup_previous_docs_tracking",
        "create_func": "create_docs_tracking_issue",
    },
    "epic-planner.md": {
        "prefix": "AUTO-EPIC",
        "tracking_type": "Epic Planning Update",
        "cleanup_func": "cleanup_previous_epic_planner_tracking",
        "create_func": "create_epic_planner_tracking_issue",
    },
    "human-liaison.md": {
        "prefix": "AUTO-LIAISON",
        "tracking_type": "Human Activity Report",
        "cleanup_func": "cleanup_previous_liaison_tracking",
        "create_func": "create_liaison_tracking_issue",
    },
    "spec-updater.md": {
        "prefix": "AUTO-SPEC",
        "tracking_type": "Specification Update",
        "cleanup_func": "cleanup_previous_spec_tracking",
        "create_func": "create_spec_tracking_issue",
    },
    "test-infra-improver.md": {
        "prefix": "AUTO-INF-POOL",
        "tracking_type": "Infrastructure Analysis",
        "cleanup_func": "cleanup_previous_infra_tracking",
        "create_func": "create_infra_tracking_issue",
    },
}


def update_agent_file(filepath, config):
    """Update a single agent file"""
    print(f"\nProcessing {filepath}...")

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

    # Find the automation tracking section
    tracking_start = content.find("## Automation Tracking System")
    if tracking_start == -1:
        print(
            f"  WARNING: Could not find '## Automation Tracking System' in {filepath}"
        )
        return False

    # Find the next section (usually starts with ##)
    next_section = content.find("\n## ", tracking_start + 1)
    if next_section == -1:
        next_section = content.find("\n---", tracking_start + 1)

    if next_section == -1:
        print(f"  WARNING: Could not find end of tracking section in {filepath}")
        return False

    # Extract the old tracking section
    old_section = content[tracking_start:next_section]

    # Create the new tracking section
    new_section = f"""## Automation Tracking System

**Updated**: This agent uses the centralized automation-tracking-manager subagent for all tracking operations.

### Tracking Issue Format
- **Health Reports**: `[{config["prefix"]}] {config["tracking_type"]} (Cycle N)`
- **Announcements**: `[{config["prefix"]}] Announce: <message summary>`
- **Labels**: "Automation Tracking" + any relevant priority labels

### Tracking Operations

All tracking operations are now handled by the automation-tracking-manager subagent:

```bash
# Create a new tracking issue (closes previous automatically)
task automation-tracking-manager "CREATE_TRACKING_ISSUE" \\
  --agent-prefix "{config["prefix"]}" \\
  --tracking-type "{config["tracking_type"]}" \\
  --body "$tracking_body" \\
  --repo-owner "$owner" \\
  --repo-name "$repo"

# Update current tracking issue with a comment
task automation-tracking-manager "UPDATE_TRACKING_ISSUE" \\
  --agent-prefix "{config["prefix"]}" \\
  --tracking-type "{config["tracking_type"]}" \\
  --comment "$update_comment" \\
  --repo-owner "$owner" \\
  --repo-name "$repo"

# Get the next cycle number
next_cycle=$(task automation-tracking-manager "GET_NEXT_CYCLE_NUMBER" \\
  --agent-prefix "{config["prefix"]}" \\
  --tracking-type "{config["tracking_type"]}" \\
  --repo-owner "$owner" \\
  --repo-name "$repo")

# Read tracking state from latest issue
tracking_state=$(task automation-tracking-manager "READ_TRACKING_STATE" \\
  --agent-prefix "{config["prefix"]}" \\
  --tracking-type "{config["tracking_type"]}" \\
  --repo-owner "$owner" \\
  --repo-name "$repo")
```"""

    # Check if there are announcement functions to preserve
    if "create_.*_announcement_issue" in old_section:
        # Extract announcement functions
        announcement_match = re.search(
            r"(# Create.*announcement.*?function create_.*_announcement_issue.*?}\n)",
            old_section,
            re.DOTALL,
        )
        if announcement_match:
            new_section += (
                "\n\n### Announcement Functions\n\n```bash\n"
                + announcement_match.group(1)
                + "```"
            )

    # Replace the old section with the new one
    new_content = content[:tracking_start] + new_section + content[next_section:]

    # Now update the cleanup function calls
    new_content = new_content.replace(f"        {config['cleanup_func']}\n", "")

    # Update the create function calls
    create_pattern = f"        {config['create_func']} .*?$"
    replacement = f"""        # Use automation-tracking-manager to create tracking issue
        result=$(task automation-tracking-manager "CREATE_TRACKING_ISSUE" \\
          --agent-prefix "{config["prefix"]}" \\
          --tracking-type "{config["tracking_type"]}" \\
          --body "$tracking_body" \\
          --repo-owner "$owner" \\
          --repo-name "$repo")
        
        # Extract issue number and cycle from result
        issue_number=$(echo "$result" | grep "ISSUE_NUMBER=" | cut -d'=' -f2)
        cycle_number=$(echo "$result" | grep "CYCLE_NUMBER=" | cut -d'=' -f2)
        
        # Update cycle for next iteration
        cycle=$cycle_number"""

    new_content = re.sub(create_pattern, replacement, new_content, flags=re.MULTILINE)

    # Update initial cycle setup
    cycle_pattern = r"(```\n)(cycle = 0|cycle=0)\n"
    cycle_replacement = f"""\\1# Get initial cycle number from tracking manager
cycle=$(task automation-tracking-manager "GET_NEXT_CYCLE_NUMBER" \\
  --agent-prefix "{config["prefix"]}" \\
  --tracking-type "{config["tracking_type"]}" \\
  --repo-owner "$owner" \\
  --repo-name "$repo")

# If this returns empty or 1, we're starting fresh
if [[ -z "$cycle" || "$cycle" == "1" ]]; then
    cycle=1
else
    # We're resuming, so use the cycle we got
    cycle=$((cycle - 1))  # Will be incremented in loop
fi
"""

    new_content = re.sub(cycle_pattern, cycle_replacement, new_content)

    # Write the updated content
    with open(filepath, "w") as f:
        f.write(new_content)

    print(f"  ✓ Updated {filepath}")
    return True


def main():
    """Main function"""
    agents_dir = "/app/.opencode/agents"

    for filename, config in agents.items():
        filepath = os.path.join(agents_dir, filename)
        if os.path.exists(filepath):
            update_agent_file(filepath, config)
        else:
            print(f"  ERROR: File not found: {filepath}")


if __name__ == "__main__":
    main()
