#!/usr/bin/env python3
"""
Generate a comprehensive list of all Tailwind default color instances.
Excludes test files and backup files.
"""

import re
import subprocess
from collections import defaultdict
from pathlib import Path

# Patterns to search for
PATTERNS = [
    r'text-gray-',
    r'bg-gray-',
    r'border-gray-',
    r'text-blue-',
    r'bg-blue-',
    r'border-blue-',
    r'text-red-',
    r'bg-red-',
    r'border-red-',
    r'text-green-',
    r'bg-green-',
    r'border-green-',
    r'text-yellow-',
    r'bg-yellow-',
    r'text-purple-',
    r'bg-purple-',
    r'text-pink-',
    r'bg-pink-',
    r'text-indigo-',
    r'bg-indigo-',
    r'text-orange-',
    r'bg-orange-',
    r'from-gray-',
    r'to-gray-',
    r'from-blue-',
    r'to-blue-',
]

# Combine patterns
PATTERN = '|'.join(PATTERNS)

def find_instances():
    """Find all Tailwind default color instances."""
    root = Path(__file__).parent.parent / 'apps' / 'web' / 'src'
    
    instances = defaultdict(list)
    
    # Find all .tsx and .ts files
    for file_path in root.rglob('*.tsx'):
        if 'ui.backup' in str(file_path) or file_path.name.endswith('.test.tsx'):
            continue
        check_file(file_path, instances)
    
    for file_path in root.rglob('*.ts'):
        if 'ui.backup' in str(file_path) or file_path.name.endswith('.test.ts'):
            continue
        check_file(file_path, instances)
    
    return instances

def check_file(file_path, instances):
    """Check a file for Tailwind default colors."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            for line_num, line in enumerate(f, 1):
                if re.search(PATTERN, line):
                    # Extract the color class
                    matches = re.findall(r'(' + PATTERN + r'[^\s"\'`)]+)', line)
                    if matches:
                        # Get relative path
                        rel_path = file_path.relative_to(Path(__file__).parent.parent)
                        instances[str(rel_path)].append({
                            'line': line_num,
                            'content': line.strip(),
                            'colors': matches
                        })
    except Exception as e:
        print(f"Error reading {file_path}: {e}", file=sys.stderr)

def generate_markdown(instances):
    """Generate markdown documentation."""
    output = []
    output.append("# Complete List of Remaining Tailwind Default Color Instances\n")
    output.append("**Generated**: Automatically generated list\n")
    output.append(f"**Total Files**: {len(instances)}\n")
    
    total_instances = sum(len(v) for v in instances.values())
    output.append(f"**Total Instances**: {total_instances}\n")
    output.append("**Status**: Action 9.1.1.3 - In Progress (294 instances migrated, ~19.7% complete)\n")
    
    output.append("\n## Usage\n")
    output.append("This document lists all remaining Tailwind default color instances organized by file path.\n")
    output.append("Each entry includes:\n")
    output.append("- File path\n")
    output.append("- Line number\n")
    output.append("- Color classes found\n")
    output.append("- Full line context\n")
    
    output.append("\n## Migration Guidelines\n")
    output.append("Refer to `TAILWIND_COLORS_AUDIT.md` for color mapping:\n")
    output.append("- `text-gray-*` → `text-kodo-content-dim` or `text-kodo-text-main`\n")
    output.append("- `bg-gray-*` → `bg-kodo-graphite`, `bg-kodo-ink`, `bg-kodo-steel`, etc.\n")
    output.append("- `border-gray-*` → `border-kodo-steel`\n")
    output.append("- `text-blue-*` → `text-kodo-cyan` (when appropriate)\n")
    output.append("- Other colors: Map to appropriate Kodo design system colors\n")
    
    output.append("\n## Files with Tailwind Default Colors\n")
    output.append("\n---\n")
    
    # Sort files alphabetically
    for file_path in sorted(instances.keys()):
        file_instances = instances[file_path]
        output.append(f"\n### {file_path}\n")
        output.append(f"**Total instances in file**: {len(file_instances)}\n")
        
        for inst in file_instances:
            colors_str = ', '.join(f"`{c}`" for c in inst['colors'])
            output.append(f"\n- **Line {inst['line']}**: {colors_str}\n")
            output.append(f"  ```tsx\n")
            output.append(f"  {inst['content']}\n")
            output.append(f"  ```\n")
        
        output.append("\n---\n")
    
    return ''.join(output)

if __name__ == '__main__':
    import sys
    instances = find_instances()
    markdown = generate_markdown(instances)
    
    output_file = Path(__file__).parent.parent / 'apps' / 'web' / 'docs' / 'TAILWIND_INSTANCES_FULL_LIST.md'
    output_file.write_text(markdown, encoding='utf-8')
    
    total = sum(len(v) for v in instances.values())
    print(f"Generated list with {total} instances across {len(instances)} files")
    print(f"Output saved to: {output_file}")
