"""Auto-fixer for sdkspindle issues.

Currently supports:
  - MISSING_IMPORT: Adds missing import statements
  - LISTOF_VARARGS: Removes unnecessary listOf() wrappers
"""

import re
from pathlib import Path


def apply_fixes(issues: list, files: list, sdk: dict) -> int:
    """Apply auto-fixes for fixable issues. Returns count of fixes applied."""
    # Group fixes by file
    fixes_by_file = {}
    for issue in issues:
        if issue.fix:
            if issue.file not in fixes_by_file:
                fixes_by_file[issue.file] = []
            fixes_by_file[issue.file].append(issue)

    total_fixed = 0
    for filepath, file_issues in fixes_by_file.items():
        path = Path(filepath)
        if not path.exists():
            continue

        content = path.read_text(encoding="utf-8")
        lines = content.split("\n")
        modified = False

        # Collect import additions (deduplicate)
        imports_to_add = set()
        for issue in file_issues:
            fix = issue.fix
            if fix["type"] == "add_import":
                imports_to_add.add(fix["import"])

        # Add missing imports after the last existing import
        if imports_to_add:
            last_import_idx = -1
            for i, line in enumerate(lines):
                if line.strip().startswith("import "):
                    last_import_idx = i

            if last_import_idx >= 0:
                # Filter out imports that already exist
                existing_imports = set(line.strip() for line in lines if line.strip().startswith("import "))
                new_imports = [imp for imp in sorted(imports_to_add) if imp not in existing_imports]
                if new_imports:
                    for j, imp in enumerate(new_imports):
                        lines.insert(last_import_idx + 1 + j, imp)
                    total_fixed += len(new_imports)
                    modified = True

        # Apply line-level fixes (listOf removal, etc.)
        # Re-read lines after potential import insertion
        for issue in file_issues:
            fix = issue.fix
            if fix and fix["type"] == "remove_listof":
                line_idx = fix.get("line", issue.line - 1)
                if 0 <= line_idx < len(lines):
                    old_line = lines[line_idx]
                    # Simple listOf() removal: .contents(listOf(X)) -> .contents(X)
                    new_line = re.sub(r'listOf\((.+?)\)', r'\1', old_line)
                    if new_line != old_line:
                        lines[line_idx] = new_line
                        total_fixed += 1
                        modified = True

        if modified:
            path.write_text("\n".join(lines), encoding="utf-8")

    return total_fixed
