#!/usr/bin/env python3
"""
Fix the remaining broken require paths after DC-005 refactor.

Two patterns to fix:
1. `require('./src/...')` and `require('../../src/...')` and `require('../../../src/...')`
   in files inside `src/` directories → should be `require('../...')` (relative to src/)
2. `require('../../../src/...')` in test files in `__tests__/` → should be `require('../src/...')`
"""
import os
import re
from pathlib import Path

DASHCADDY_API = Path('/root/dashcaddy-krystie/dashcaddy-api')

# Pattern to match require('../../../src/X/Y') and capture
# We need to detect the file's location and rewrite based on that
# A simple approach: find any require that contains 'src/' in the path,
# and rewrite it to be relative to the file's location.

def fix_file(filepath: Path) -> bool:
    """Returns True if file was changed."""
    content = filepath.read_text()
    original = content

    # Find the file's directory relative to dashcaddy-api root
    rel_dir = filepath.parent.relative_to(DASHCADDY_API)
    depth = len(rel_dir.parts)

    # If file is in src/X/Y/file.js, depth is 3 (src, X, Y)
    # If file is in __tests__/file.js, depth is 1
    # If file is in __tests__/routes/file.js, depth is 2

    # Find all require() calls that contain 'src/'
    # Pattern: require('(.....)*src/path')
    def replacer(match):
        quote = match.group(1)  # the quote char
        path = match.group(2)   # the path inside quotes
        # Calculate what the path SHOULD be
        if 'src/' not in path:
            return match.group(0)

        # Extract the part after 'src/'
        idx = path.find('src/')
        after_src = path[idx + 4:]  # everything after 'src/'

        if filepath.parts[-3] == 'src':
            # File is in src/X/file.js - depth 3
            # Should be '../<after_src>'
            new_path = '../' + after_src
        elif filepath.parts[-4] == 'src':
            # File is in src/X/Y/file.js - depth 4
            # Should be '../../<after_src>'
            new_path = '../../' + after_src
        elif filepath.parts[-2] == '__tests__' or filepath.parent.name == '__tests__':
            # File is in __tests__/file.js - depth 1 (relative to api root)
            # Should be '../src/<after_src>'
            new_path = '../src/' + after_src
        elif filepath.parts[-2] == 'routes' and filepath.parts[-3] == '__tests__':
            # File is in __tests__/routes/file.js - depth 2
            # Should be '../../src/<after_src>'
            new_path = '../../src/' + after_src
        elif 'src' in rel_dir.parts:
            # Other src nested location
            # Count how many .. we need
            src_depth = len(rel_dir.parts) - list(rel_dir.parts).index('src') - 1
            new_path = '../' * src_depth + after_src
        else:
            # Other location, leave it
            return match.group(0)

        return f"require({quote}{new_path}{quote})"

    new_content = re.sub(
        r"require\((['\"])([^'\"]*src/[^'\"]*)\1\)",
        replacer,
        content
    )

    if new_content != original:
        filepath.write_text(new_content)
        return True
    return False


def main():
    changed = []
    for js_file in DASHCADDY_API.rglob('*.js'):
        # Skip node_modules
        if 'node_modules' in js_file.parts:
            continue
        if fix_file(js_file):
            changed.append(str(js_file.relative_to(DASHCADDY_API)))

    print(f"Changed {len(changed)} files:")
    for f in changed:
        print(f"  {f}")


if __name__ == '__main__':
    main()
