#!/usr/bin/env python3
"""
Script to complete audit router registration in all remaining services.
"""

import re
from pathlib import Path

BASE_DIR = Path(__file__).parent.parent / "services"

# Services that still need updates (suppliers, pos, training, notification, external, forecasting)
SERVICES = ['suppliers', 'pos', 'training', 'notification', 'external', 'forecasting']

def update_service(service_name):
    main_file = BASE_DIR / service_name / "app" / "main.py"

    if not main_file.exists():
        print(f"⚠️  {service_name}: main.py not found")
        return False

    content = main_file.read_text()
    modified = False

    # Check if audit is already imported
    if 'import.*audit' in content or ', audit' in content:
        print(f"✓ {service_name}: audit already imported")
    else:
        # Add audit import - find the from .api or from app.api import line
        patterns = [
            (r'(from \.api import [^)]+)(\))', r'\1, audit\2'),  # Multi-line with parentheses
            (r'(from \.api import .+)', r'\1, audit'),  # Single line with .api
            (r'(from app\.api import [^)]+)(\))', r'\1, audit\2'),  # Multi-line with app.api
            (r'(from app\.api import .+)', r'\1, audit'),  # Single line with app.api
        ]

        for pattern, replacement in patterns:
            new_content = re.sub(pattern, replacement, content)
            if new_content != content:
                content = new_content
                modified = True
                print(f"✓ {service_name}: added audit import")
                break

        if not modified:
            print(f"⚠️  {service_name}: could not find import pattern, needs manual update")
            return False

    # Check if audit router is already registered
    if 'service.add_router(audit.router)' in content:
        print(f"✓ {service_name}: audit router already registered")
    else:
        # Find the last service.add_router line and add audit router after it
        lines = content.split('\n')
        last_router_index = -1

        for i, line in enumerate(lines):
            if 'service.add_router(' in line and 'audit' not in line:
                last_router_index = i

        if last_router_index != -1:
            # Insert audit router after the last router registration
            lines.insert(last_router_index + 1, 'service.add_router(audit.router)')
            content = '\n'.join(lines)
            modified = True
            print(f"✓ {service_name}: added audit router registration")
        else:
            print(f"⚠️  {service_name}: could not find router registration pattern, needs manual update")
            return False

    if modified:
        main_file.write_text(content)
        print(f"✅ {service_name}: updated successfully")
    else:
        print(f"ℹ️  {service_name}: no changes needed")

    return True

def main():
    print("Completing audit router registration in remaining services...\n")

    success_count = 0
    for service in SERVICES:
        if update_service(service):
            success_count += 1
        print()

    print(f"\nCompleted: {success_count}/{len(SERVICES)} services updated successfully")

if __name__ == "__main__":
    main()
