#!/usr/bin/env python

import os
import sys
import shutil
import stat
import subprocess
from pathlib import Path

# Add the project directory to the Python path
sys.path.insert(0, os.path.dirname(__file__))

# Set production settings
os.environ["DJANGO_SETTINGS_MODULE"] = "branch_system.settings_production"

# Import Django modules after setting the environment
import django
django.setup()

from django.conf import settings
from django.core.management import call_command

def print_header(message):
    print(f"\n{'=' * 60}")
    print(f" {message}")
    print(f"{'=' * 60}\n")

def print_step(message):
    print(f"🔧 {message}")

def print_success(message):
    print(f"✅ {message}")

def print_warning(message):
    print(f"⚠️ {message}")

def backup_files():
    print_step("Creating backup of critical files...")
    
    backup_dir = Path(settings.BASE_DIR) / 'backups'
    backup_dir.mkdir(exist_ok=True)
    
    # Files to backup
    files_to_backup = [
        Path(settings.BASE_DIR) / 'branch_system' / 'settings_production.py',
        Path(settings.BASE_DIR) / 'branch_system' / 'urls.py',
        Path(settings.BASE_DIR) / 'branch_system' / 'wsgi.py',
        Path(settings.BASE_DIR) / '.htaccess',
    ]
    
    for file_path in files_to_backup:
        if file_path.exists():
            backup_path = backup_dir / f"{file_path.name}.bak"
            shutil.copy2(file_path, backup_path)
            print_success(f"Backed up {file_path} to {backup_path}")
    
    print_success("Backup completed")

def deploy_fixes():
    print_step("Deploying media and static file fixes...")
    
    # Run the fix_media_images.py script
    try:
        subprocess.run([sys.executable, 'fix_media_images.py'], check=True)
        print_success("Successfully ran fix_media_images.py")
    except subprocess.CalledProcessError as e:
        print_warning(f"Error running fix_media_images.py: {e}")
        print_step("Continuing with deployment...")
    
    # Run the test script
    try:
        subprocess.run([sys.executable, 'test_media_access.py'], check=True)
        print_success("Successfully ran test_media_access.py")
    except subprocess.CalledProcessError as e:
        print_warning(f"Error running test_media_access.py: {e}")
        print_step("Continuing with deployment...")

def update_templates():
    print_step("Updating templates to include CSS and JS fixes...")
    
    # Find base template
    base_template_path = Path(settings.BASE_DIR) / 'templates' / 'base.html'
    if base_template_path.exists():
        with open(base_template_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        # Check if our CSS and JS are already included
        css_included = 'table-fix.css' in content
        js_included = 'table-fix.js' in content
        
        if not css_included or not js_included:
            # Find the </head> tag
            head_end_pos = content.find('</head>')
            if head_end_pos != -1:
                # Add our CSS and JS before the </head> tag
                includes = ''
                if not css_included:
                    includes += '\n    <!-- Fix for client names and images -->\n'
                    includes += '    <link rel="stylesheet" href="{% static \'css/table-fix.css\' %}">\n'
                if not js_included:
                    includes += '    <script src="{% static \'js/table-fix.js\' %}" defer></script>\n'
                
                updated_content = content[:head_end_pos] + includes + content[head_end_pos:]
                
                with open(base_template_path, 'w', encoding='utf-8') as f:
                    f.write(updated_content)
                
                print_success(f"Updated {base_template_path} to include CSS and JS fixes")
            else:
                print_warning(f"Could not find </head> tag in {base_template_path}")
        else:
            print_success(f"CSS and JS fixes already included in {base_template_path}")
    else:
        print_warning(f"Base template not found: {base_template_path}")
        
        # Try to find other templates that might include <head>
        templates_dir = Path(settings.BASE_DIR) / 'templates'
        if templates_dir.exists():
            for root, dirs, files in os.walk(templates_dir):
                for file in files:
                    if file.endswith('.html'):
                        template_path = Path(root) / file
                        with open(template_path, 'r', encoding='utf-8', errors='ignore') as f:
                            content = f.read()
                        
                        if '</head>' in content and ('table-fix.css' not in content or 'table-fix.js' not in content):
                            print_step(f"Found template with </head>: {template_path}")
                            # Add our CSS and JS before the </head> tag
                            head_end_pos = content.find('</head>')
                            includes = '\n    <!-- Fix for client names and images -->\n'
                            if 'table-fix.css' not in content:
                                includes += '    <link rel="stylesheet" href="{% static \'css/table-fix.css\' %}">\n'
                            if 'table-fix.js' not in content:
                                includes += '    <script src="{% static \'js/table-fix.js\' %}" defer></script>\n'
                            
                            updated_content = content[:head_end_pos] + includes + content[head_end_pos:]
                            
                            with open(template_path, 'w', encoding='utf-8') as f:
                                f.write(updated_content)
                            
                            print_success(f"Updated {template_path} to include CSS and JS fixes")

def create_deployment_instructions():
    print_step("Creating deployment instructions...")
    
    instructions = """
# HAVEN GRAZURI INVESTMENT LIMITED- Media & Static Files Deployment Instructions

## Overview
This document provides instructions for deploying the media and static file fixes to the production server.

## Prerequisites
- Access to the production server via SSH or FTP
- Ability to run Python scripts on the server
- Ability to restart the web server

## Deployment Steps

### 1. Upload the Fix Scripts
Upload the following files to the production server:
- fix_media_images.py
- test_media_access.py
- deploy_media_fix.py

### 2. Run the Deployment Script
```bash
python deploy_media_fix.py
```

### 3. Restart the Web Server
Restart Apache or your web server:
```bash
sudo service apache2 restart
```
Or through cPanel's interface.

### 4. Verify the Fixes
Access the website and verify that:
- Images are loading correctly
- Client names are not overlapping
- Static files (CSS, JS) are loading

## Troubleshooting

### Images Still Not Loading
1. Check file permissions:
   ```bash
   chmod -R 755 media/
   find media/ -type f -exec chmod 644 {} \;
   ```

2. Verify .htaccess is being read:
   Add a test rule to .htaccess and see if it takes effect.

3. Check Apache error logs:
   ```bash
   tail -f /var/log/apache2/error.log
   ```

4. Temporarily enable DEBUG mode:
   Edit branch_system/settings_production.py and set DEBUG = True

### Client Names Still Overlapping
1. Verify the CSS is being loaded:
   Check browser developer tools for 404 errors.

2. Manually add the CSS class to elements:
   Edit the templates to add the 'client-name' class to relevant elements.

## Rollback Plan
If issues persist, you can restore the backup files from the 'backups' directory:
```bash
cp backups/settings_production.py.bak branch_system/settings_production.py
cp backups/urls.py.bak branch_system/urls.py
cp backups/wsgi.py.bak branch_system/wsgi.py
cp backups/.htaccess.bak .htaccess
```

Then restart the web server.
"""
    
    instructions_path = Path(settings.BASE_DIR) / 'MEDIA_FIX_DEPLOYMENT.md'
    with open(instructions_path, 'w') as f:
        f.write(instructions)
    
    print_success(f"Created deployment instructions: {instructions_path}")

def main():
    print_header("HAVEN GRAZURI VESTMENT LIMITED- Media & Static Files Deployment")
    
    # Create backups
    backup_files()
    
    # Deploy fixes
    deploy_fixes()
    
    # Update templates
    update_templates()
    
    # Create deployment instructions
    create_deployment_instructions()
    
    print_header("DEPLOYMENT COMPLETED")
    print("\n📋 Next Steps:")
    print("1. Review the MEDIA_FIX_DEPLOYMENT.md file for detailed instructions")
    print("2. Upload the fix scripts to the production server")
    print("3. Run the deployment script on the production server")
    print("4. Restart the web server")
    print("5. Verify that images are loading and client names are displaying correctly")
    print("\n🔍 If issues persist:")
    print("- Check server error logs")
    print("- Verify file permissions")
    print("- Ensure .htaccess is being read by Apache")
    print("- Consider temporarily setting DEBUG=True to diagnose issues")

if __name__ == "__main__":
    main()