#!/usr/bin/env python3
"""
Mark a correction as applied.
Updates times_applied, last_applied, and optionally confirmed_by.
"""

import sys
import os
import re
from datetime import datetime
from pathlib import Path

CORRECTIONS_DIR = Path("/home/aria/.openclaw/workspace/agency/corrections")

def mark_applied(cor_id: str, confirmed_by: str = None):
    """Mark a correction as applied."""
    
    # Find the file
    pattern = f"{cor_id}-*.yaml"
    matches = list(CORRECTIONS_DIR.glob(pattern))
    
    if not matches:
        # Try exact match
        matches = list(CORRECTIONS_DIR.glob(f"{cor_id}.yaml"))
    
    if not matches:
        print(f"❌ Correction {cor_id} not found")
        return False
    
    filepath = matches[0]
    
    # Read current content
    with open(filepath, 'r') as f:
        content = f.read()
    
    # Update times_applied
    times_match = re.search(r'times_applied:\s*(\d+)', content)
    if times_match:
        current = int(times_match.group(1))
        content = re.sub(
            r'times_applied:\s*\d+',
            f'times_applied: {current + 1}',
            content
        )
    
    # Update last_applied
    now = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
    content = re.sub(
        r'last_applied:\s*\S+',
        f'last_applied: "{now}"',
        content
    )
    
    # Update confirmed_by if provided
    if confirmed_by:
        # Parse existing confirmed_by list
        confirmed_match = re.search(r'confirmed_by:\s*\[(.*?)\]', content, re.DOTALL)
        if confirmed_match:
            existing = confirmed_match.group(1).strip()
            if existing:
                # Add to existing list
                if confirmed_by not in existing:
                    new_list = f'{existing}, "{confirmed_by}"'
                else:
                    new_list = existing
            else:
                new_list = f'"{confirmed_by}"'
            content = re.sub(
                r'confirmed_by:\s*\[.*?\]',
                f'confirmed_by: [{new_list}]',
                content,
                flags=re.DOTALL
            )
    
    # Write back
    with open(filepath, 'w') as f:
        f.write(content)
    
    print(f"✅ {cor_id} marked as applied (times_applied +1)")
    if confirmed_by:
        print(f"   Confirmed by: {confirmed_by}")
    
    return True

def main():
    if len(sys.argv) < 2:
        print("Usage: mark_applied.py <COR-XXX> [confirmed_by]")
        print("Example: mark_applied.py COR-007 nick")
        sys.exit(1)
    
    cor_id = sys.argv[1].upper()
    confirmed_by = sys.argv[2] if len(sys.argv) > 2 else None
    
    success = mark_applied(cor_id, confirmed_by)
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()
