import os
import re
from pathlib import Path

# Config
SOURCE_DIR = Path(".claude/commands")
DEST_DIR = Path(".agent/workflows")
DEST_DIR.mkdir(parents=True, exist_ok=True)

def parse_claude_command(content):
    """Extract frontmatter and command script."""
    # 1. Extract YAML Frontmatter (Regex Only)
    frontmatter_match = re.search(r'^---\n(.*?)\n---', content, re.DOTALL)
    metadata = {}
    if frontmatter_match:
        yaml_text = frontmatter_match.group(1)
        # Simple key: value parser
        for line in yaml_text.splitlines():
            if ':' in line:
                key, val = line.split(':', 1)
                metadata[key.strip()] = val.strip()
    
    # 2. Extract Description (Title) from first H1
    h1_match = re.search(r'^#\s+(.*)', content, re.MULTILINE)
    title = h1_match.group(1) if h1_match else "Custom Command"

    # 3. Extract the Command (!`...`)
    # Claude Code uses !`script` syntax. We catch everything inside !`...`
    # Note: Regex needs to handle multiline.
    cmd_match = re.search(r'!`(.*?)`', content, re.DOTALL)
    script = ""
    if cmd_match:
        script = cmd_match.group(1).strip()
    
    return metadata, title, script

def convert_to_workflow(filename, metadata, title, script):
    """Generate Antigravity Workflow Content."""
    # Workflow Frontmatter
    wf_content = "---\n"
    wf_content += f"description: {metadata.get('description', title)}\n"
    wf_content += "---\n\n"
    
    wf_content += f"# {title}\n\n"
    wf_content += f"{metadata.get('description', '')}\n\n"
    
    if metadata.get('argument-hint'):
        wf_content += f"> Usage: `{filename} {metadata.get('argument-hint')}`\n\n"
        
    wf_content += "1. Execute the command\n"
    wf_content += "// turbo\n"
    wf_content += "```bash\n"
    
    # In Claude Code, $ARGUMENTS is injected. 
    # In Antigravity, we might need to handle args differently or ask user.
    # For now, we assume the user will replace placeholders or simple direct execution.
    # We'll replace $ARGUMENTS with empty string or a placeholder note if needed.
    # Actually, let's keep it as is, but add a note to the user in the prompt.
    
    processed_script = script.replace('python3', 'python3') # no-op, just placeholder
    
    wf_content += processed_script + "\n"
    wf_content += "```\n"
    
    return wf_content

def main():
    print(f"Migrating commands from {SOURCE_DIR} to {DEST_DIR}...")
    
    count = 0
    for file_path in SOURCE_DIR.glob("*.md"):
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                
            metadata, title, script = parse_claude_command(content)
            
            if not script:
                print(f"Skipping {file_path.name}: No execution script found.")
                continue
                
            # Create Workflow
            wf_filename = file_path.name # e.g. log-diet.md
            wf_content = convert_to_workflow(file_path.stem, metadata, title, script)
            
            dest_path = DEST_DIR / wf_filename
            with open(dest_path, 'w', encoding='utf-8') as f:
                f.write(wf_content)
                
            print(f"✅ Converted: {file_path.name} -> {dest_path}")
            count += 1
            
        except Exception as e:
            print(f"❌ Failed to convert {file_path.name}: {e}")
            
    print(f"\nMigration Complete. {count} workflows created.")

if __name__ == "__main__":
    main()
