#!/usr/bin/env python3 """ Script to fix the corrupted EMR models.py file. This script will: 1. Remove the Encounter and EncounterManager classes 2. Add proper imports from core 3. Update all patient FK references from 'patients.PatientProfile' to 'core.Patient' """ import re import sys from pathlib import Path def fix_emr_models(): """Fix the EMR models file.""" # Read the current file emr_models_path = Path('emr/models.py') if not emr_models_path.exists(): print(f"Error: {emr_models_path} not found!") return False print(f"Reading {emr_models_path}...") content = emr_models_path.read_text(encoding='utf-8') # Step 1: Fix the imports section print("Step 1: Fixing imports...") # Find the imports section and replace it imports_pattern = r'"""[\s\S]*?"""([\s\S]*?)(?=class\s+\w+\(models\.Model\):)' new_imports = ''' import uuid from django.db import models from django.core.validators import RegexValidator, MinValueValidator, MaxValueValidator from django.utils import timezone from django.conf import settings from datetime import timedelta, datetime, time import json from django.core.exceptions import ValidationError # Import core models from core.models import Encounter, Patient, TenantScopedModel # Note: Encounter model has been moved to core.models # All patient references now use core.Patient instead of patients.PatientProfile ''' # Replace everything from docstring to first class content = re.sub( r'("""[\s\S]*?""")([\s\S]*?)(?=class VitalSigns)', r'\1' + new_imports + 'class VitalSigns', content, count=1 ) # Step 2: Replace all patient FK references print("Step 2: Updating patient FK references...") content = content.replace("'patients.PatientProfile'", "'core.Patient'") # Step 3: Write the fixed content print(f"Step 3: Writing fixed content to {emr_models_path}...") emr_models_path.write_text(content, encoding='utf-8') print("✅ EMR models file fixed successfully!") print("\nChanges made:") print(" - Added imports from core.models (Encounter, Patient, TenantScopedModel)") print(" - Removed duplicate Encounter and EncounterManager classes") print(" - Updated all patient FK references to use 'core.Patient'") return True if __name__ == '__main__': success = fix_emr_models() sys.exit(0 if success else 1)