import os
import re

# =============================================================================
# CONFIGURATION
# =============================================================================

# 1. Frontend .env (The most critical one to update)
#    This tells the React/Next.js app where to find the backend API.
FRONTEND_ENV_PATH = r"C:\wamp64\www\monrita-main\frontend\.env"
FRONTEND_KEY = "NEXT_PUBLIC_API_BASE"

# 2. Backend .env (Optional, for CORS)
#    This tells the Backend which frontend URLs are allowed to connect.
BACKEND_ENV_PATH = r"C:\wamp64\www\monrita-main\backend\.env"
BACKEND_CORS_KEY = "CORS_ALLOWED_ORIGINS"

# 3. Backend Data Backup (Optional, for cleaning data)
#    This file contains hardcoded URLs in the database dump.
BACKEND_DATA_PATH = r"C:\wamp64\www\monrita-main\backend\supplier_db_backup_20251114_170829.json"

# =============================================================================
# LOGIC
# =============================================================================

def update_env_file(file_path, key, new_value):
    """Updates a specific key in a .env file."""
    if not os.path.exists(file_path):
        print(f"[SKIP] File not found: {file_path}")
        return

    print(f"[UPDATE] Updating {key} in {file_path}...")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    new_lines = []
    found = False
    for line in lines:
        if line.strip().startswith(f"{key}="):
            new_lines.append(f"{key}={new_value}\n")
            found = True
        else:
            new_lines.append(line)

    if not found:
        new_lines.append(f"\n{key}={new_value}\n")

    with open(file_path, 'w', encoding='utf-8') as f:
        f.writelines(new_lines)
    print(f"   -> Set to: {new_value}")

def clean_json_dump(file_path, old_domains, new_domain):
    """Replaces hardcoded domains in a JSON dump."""
    if not os.path.exists(file_path):
        print(f"[SKIP] File not found: {file_path}")
        return

    print(f"[CLEAN] Scanning {file_path} for hardcoded URLs...")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    original_len = len(content)
    
    for old_domain in old_domains:
        # Replace http://old_domain with http://new_domain
        # You might want to be more specific with regex if needed
        content = content.replace(f"http://{old_domain}", f"http://{new_domain}")
        content = content.replace(f"https://{old_domain}", f"https://{new_domain}")

    if len(content) != original_len: # This check is naive for replacements of same length, but good enough for now
        # Or just check if content changed
        pass

    # For this specific file, we know it has localhost:8000 and 172.25.220.112:8000
    # We probably want to replace them with the new API base or just a placeholder.
    # NOTE: This is risky if you don't know exactly what the data is used for.
    # For now, I will just print a warning instead of overwriting, unless you uncomment the write.
    
    matches = re.findall(r'http://(localhost|172\.25\.\d+\.\d+):8000', content)
    if matches:
        print(f"   -> Found {len(matches)} hardcoded development URLs in data.")
        print("   -> To fix these, uncomment the write block in the script.")
        # with open(file_path, 'w', encoding='utf-8') as f:
        #    f.write(content)

def main():
    # 1. Determine the new IP/Host (You can automate this or pass it as arg)
    # For now, let's assume we want to set it to the current machine's IP or localhost
    import socket
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)
    
    print(f"Detected Local IP: {local_ip}")
    
    # Construct the new URLs
    # Frontend needs to know where Backend is:
    new_api_base = f"http://{local_ip}/monrita-main/backend/public/api/v1"
    
    # Backend needs to know where Frontend is (for CORS):
    # Assuming Frontend runs on port 3000
    new_frontend_origin = f"http://{local_ip}:3000"

    # 2. Execute Updates
    update_env_file(FRONTEND_ENV_PATH, FRONTEND_KEY, new_api_base)
    
    # Optional: Update Backend CORS to allow the new frontend IP
    # update_env_file(BACKEND_ENV_PATH, BACKEND_CORS_KEY, f"http://localhost:3000,{new_frontend_origin}")

    # Optional: Clean the data dump
    # clean_json_dump(BACKEND_DATA_PATH, ["localhost:8000", "172.25.220.112:8000"], f"{local_ip}/monrita-main/backend")

if __name__ == "__main__":
    main()
