#!/usr/bin/env python
"""
Deploy Chart of Accounts & PDF Reports to Production
Uploads modified files to production server and restarts the application
"""

import os
import sys
import subprocess
from pathlib import Path

# Configuration
PRODUCTION_SERVER = "grazuri.uzuriapps.xyz"
PRODUCTION_USER = "xygbfpsg"  # Update if needed
PRODUCTION_PATH = "/home/xygbfpsg/public_html/grazuri"

# Files to deploy
FILES_TO_DEPLOY = [
    "templates/reports/standalone_dashboard.html",
    "templates/reports/dashboard.html",
    "templates/reports/financial/index.html",
    "templates/reports/financial/chart_of_accounts.html",
    "templates/reports/financial/account_ledger.html",
    "accounting/pdf_reports.py",
    "reports/financial_reports_views.py",
    "reports/urls.py",
]

def print_header(text):
    """Print a formatted header"""
    print("\n" + "="*60)
    print(f"  {text}")
    print("="*60 + "\n")

def print_step(step_num, text):
    """Print a formatted step"""
    print(f"[{step_num}] {text}")

def print_success(text):
    """Print success message"""
    print(f"✓ {text}")

def print_error(text):
    """Print error message"""
    print(f"✗ ERROR: {text}")
    sys.exit(1)

def check_files_exist():
    """Check that all files to deploy exist locally"""
    print_step(1, "Checking files exist locally...")
    
    missing_files = []
    for file_path in FILES_TO_DEPLOY:
        if not os.path.exists(file_path):
            missing_files.append(file_path)
    
    if missing_files:
        print_error(f"Missing files:\n  - " + "\n  - ".join(missing_files))
    
    print_success(f"All {len(FILES_TO_DEPLOY)} files found")

def create_deployment_package():
    """Create a tar archive of files to deploy"""
    print_step(2, "Creating deployment package...")
    
    # Create a temporary directory structure
    temp_dir = "temp_deploy_chart_of_accounts"
    
    # Clean up if exists
    if os.path.exists(temp_dir):
        import shutil
        shutil.rmtree(temp_dir)
    
    # Copy files maintaining directory structure
    import shutil
    for file_path in FILES_TO_DEPLOY:
        dest_path = os.path.join(temp_dir, file_path)
        os.makedirs(os.path.dirname(dest_path), exist_ok=True)
        shutil.copy2(file_path, dest_path)
    
    # Create tar archive
    import tarfile
    archive_name = "chart_of_accounts_deployment.tar.gz"
    with tarfile.open(archive_name, "w:gz") as tar:
        tar.add(temp_dir, arcname=".")
    
    # Clean up temp directory
    shutil.rmtree(temp_dir)
    
    print_success(f"Created {archive_name}")
    return archive_name

def upload_to_production(archive_name):
    """Upload the deployment package to production"""
    print_step(3, "Uploading to production server...")
    
    # Use SCP to upload
    scp_command = f"scp {archive_name} {PRODUCTION_USER}@{PRODUCTION_SERVER}:{PRODUCTION_PATH}/"
    
    print(f"  Command: {scp_command}")
    print("  (You may be prompted for your password)")
    
    result = subprocess.run(scp_command, shell=True)
    
    if result.returncode != 0:
        print_error("Upload failed. Please check your credentials and network connection.")
    
    print_success("Files uploaded")

def deploy_on_server(archive_name):
    """SSH into server and deploy the files"""
    print_step(4, "Deploying files on server...")
    
    deploy_commands = f"""
cd {PRODUCTION_PATH} && \\
tar -xzf {archive_name} && \\
rm {archive_name} && \\
touch tmp/restart.txt && \\
echo "Deployment complete"
"""
    
    ssh_command = f'ssh {PRODUCTION_USER}@{PRODUCTION_SERVER} "{deploy_commands}"'
    
    print(f"  Executing deployment commands on server...")
    
    result = subprocess.run(ssh_command, shell=True)
    
    if result.returncode != 0:
        print_error("Deployment on server failed.")
    
    print_success("Files deployed and application restarted")

def cleanup_local(archive_name):
    """Clean up local deployment artifacts"""
    print_step(5, "Cleaning up...")
    
    if os.path.exists(archive_name):
        os.remove(archive_name)
    
    print_success("Cleanup complete")

def main():
    """Main deployment function"""
    print_header("CHART OF ACCOUNTS DEPLOYMENT TO PRODUCTION")
    
    print("This script will deploy the following files:")
    for i, file_path in enumerate(FILES_TO_DEPLOY, 1):
        print(f"  {i}. {file_path}")
    
    print(f"\nTarget server: {PRODUCTION_USER}@{PRODUCTION_SERVER}")
    print(f"Target path: {PRODUCTION_PATH}")
    
    response = input("\nContinue with deployment? (yes/no): ")
    if response.lower() not in ['yes', 'y']:
        print("Deployment cancelled.")
        sys.exit(0)
    
    try:
        # Check files
        check_files_exist()
        
        # Create package
        archive_name = create_deployment_package()
        
        # Upload
        upload_to_production(archive_name)
        
        # Deploy
        deploy_on_server(archive_name)
        
        # Cleanup
        cleanup_local(archive_name)
        
        # Success
        print_header("DEPLOYMENT SUCCESSFUL!")
        print("Next steps:")
        print("  1. Visit: https://grazuri.uzuriapps.xyz/reports/")
        print("  2. Look for 'Consolidated Financial Reports' section")
        print("  3. You should see a BLUE banner with 'Chart of Accounts'")
        print("  4. Click 'View Chart of Accounts →'")
        print("  5. Test all 4 PDF download buttons")
        print("\nIf the button doesn't appear:")
        print("  • Clear your browser cache (Ctrl+F5)")
        print("  • Wait 1-2 minutes for server restart")
        print("  • Check that you're viewing the correct URL")
        
    except Exception as e:
        print_error(f"Unexpected error: {str(e)}")

if __name__ == "__main__":
    main()
