#!/usr/bin/env python3
"""MCP Import Refactor Script.

Purpose:
    Convert absolute imports (from mcp_servers.*) to relative imports
    throughout the src/mcp_servers/noveler package.
Context:
    Part of B20 workflow Phase 3 - MCP Import Refactor & Retire Namespace Shim.
Side Effects:
    Modifies Python source files in-place.
"""
from pathlib import Path
import re


def convert_imports_in_file(file_path: Path, base_depth: int) -> tuple[int, list[str]]:
    """Convert absolute imports to relative imports in a single file.

    Args:
        file_path: Path to the Python file to process.
        base_depth: Number of '..' needed to reach noveler/ from this file's directory.
                   0 = in noveler/, 1 = one level deep (e.g., tools/), etc.

    Returns:
        Tuple of (number of replacements, list of changed lines).
    """
    content = file_path.read_text(encoding="utf-8")
    lines = content.splitlines(keepends=True)
    changes = []
    replacement_count = 0

    # Patterns to match
    # Pattern 1: from mcp_servers.noveler.xxx import ...
    # Pattern 2: from mcp_servers.noveler.xxx.yyy import ...

    prefix = ".." * base_depth if base_depth > 0 else "."

    for i, line in enumerate(lines, start=1):
        # Match: from mcp_servers.noveler.MODULE import ...
        match = re.match(r"^from mcp_servers\.noveler\.(\S+) import (.+)$", line)
        if match:
            module_path = match.group(1)  # e.g., "core.format_utils"
            imports = match.group(2)      # e.g., "format_dict, format_json_result"

            # Convert to relative
            if base_depth == 0:
                # In noveler/ root: from mcp_servers.noveler.core.xxx -> from .core.xxx
                new_line = f"from .{module_path} import {imports}\n"
            else:
                # In subdirectory: from mcp_servers.noveler.core.xxx -> from ..core.xxx
                new_line = f"from ..{module_path} import {imports}\n"

            lines[i - 1] = new_line
            changes.append(f"Line {i}: {line.strip()} -> {new_line.strip()}")
            replacement_count += 1

    if replacement_count > 0:
        file_path.write_text("".join(lines), encoding="utf-8")

    return replacement_count, changes


def main():
    """Main execution function."""
    project_root = Path(__file__).resolve().parent.parent
    noveler_root = project_root / "src" / "mcp_servers" / "noveler"

    # Define file groups by depth
    groups = [
        # Group 1: noveler/ root (depth 0)
        {
            "name": "noveler root",
            "depth": 0,
            "files": [
                noveler_root / "json_conversion_server.py",
                noveler_root / "async_json_conversion_server.py",
            ],
        },
        # Group 2: core/ (depth 1, but imports within same package)
        {
            "name": "core",
            "depth": 0,  # Same-package imports use "."
            "files": [
                noveler_root / "core" / "async_subprocess_adapter.py",
            ],
        },
        # Group 3: tests/ (depth 1)
        {
            "name": "tests",
            "depth": 1,
            "files": [
                noveler_root / "tests" / "test_command_builder.py",
                noveler_root / "tests" / "test_integration.py",
                noveler_root / "tests" / "test_response_parser.py",
                noveler_root / "tests" / "test_subprocess_adapter.py",
            ],
        },
        # Group 4: tools/ (depth 1)
        {
            "name": "tools",
            "depth": 1,
            "files": list((noveler_root / "tools").glob("*.py")),
        },
    ]

    total_files = 0
    total_replacements = 0

    print("=== MCP Import Refactor Script ===\n")

    for group in groups:
        print(f"Processing group: {group['name']}")
        group_files = 0
        group_replacements = 0

        for file_path in group["files"]:
            if not file_path.exists():
                continue

            count, changes = convert_imports_in_file(file_path, group["depth"])
            if count > 0:
                print(f"  ✓ {file_path.name}: {count} replacements")
                for change in changes:
                    print(f"    {change}")
                group_files += 1
                group_replacements += count
            else:
                print(f"  - {file_path.name}: no changes")

        print(f"  Group total: {group_files} files, {group_replacements} replacements\n")
        total_files += group_files
        total_replacements += group_replacements

    print("=== Summary ===")
    print(f"Total files modified: {total_files}")
    print(f"Total replacements: {total_replacements}")


if __name__ == "__main__":
    main()
