#!/usr/bin/env python3
"""
Script to update the Django site domain in production MySQL database.
This script updates the domain from 'example.com' to 'smarthr.ictaz.org.zm'
in the django_site table.

Usage:
    python3 update_site_domain.py

Environment variables required:
    DB_NAME - Database name
    DB_USER - Database username
    DB_PASSWORD - Database password
    DB_HOST - Database host (default: localhost)
    DB_PORT - Database port (default: 3306)
"""

import os
import sys
import mysql.connector
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Get database configuration from environment variables
DB_NAME = os.getenv('DB_NAME')
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_PORT = os.getenv('DB_PORT', '3306')

# Target site values
SITE_ID = 1
NEW_DOMAIN = 'smarthr.ictaz.org.zm'
NEW_NAME = 'ICTAZ WTLMS'

def update_site_domain():
    """Update the Django site domain in the database."""
    # Validate environment variables
    if not all([DB_NAME, DB_USER, DB_PASSWORD]):
        print("Error: Missing required environment variables (DB_NAME, DB_USER, DB_PASSWORD)")
        print("Please set these variables in your .env file or environment")
        sys.exit(1)
    
    try:
        # Connect to the database
        print(f"Connecting to MySQL database {DB_NAME} on {DB_HOST}:{DB_PORT}...")
        conn = mysql.connector.connect(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_NAME
        )
        cursor = conn.cursor()
        
        # Check current site domain
        cursor.execute("SELECT domain, name FROM django_site WHERE id = %s", (SITE_ID,))
        result = cursor.fetchone()
        
        if not result:
            print(f"Error: Site with ID {SITE_ID} not found in the database")
            conn.close()
            sys.exit(1)
        
        current_domain, current_name = result
        print(f"Current site: {current_name} - {current_domain}")
        
        # Update the site domain and name
        cursor.execute(
            "UPDATE django_site SET domain = %s, name = %s WHERE id = %s",
            (NEW_DOMAIN, NEW_NAME, SITE_ID)
        )
        conn.commit()
        
        # Verify the update
        cursor.execute("SELECT domain, name FROM django_site WHERE id = %s", (SITE_ID,))
        new_domain, new_name = cursor.fetchone()
        print(f"Site updated successfully: {new_name} - {new_domain}")
        
        conn.close()
        print("Database connection closed")
        
    except mysql.connector.Error as err:
        print(f"Database error: {err}")
        sys.exit(1)
    except Exception as e:
        print(f"Unexpected error: {e}")
        sys.exit(1)

if __name__ == "__main__":
    print("Starting site domain update script...")
    update_site_domain()
    print("Script completed successfully")
