#!/usr/bin/env python3
"""
Deploy script to update expense editing permissions
Allows admins and team leaders to edit any expense, not just pending ones
"""

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

# Production server details
PROD_HOST = "xygbfpsg@198.54.126.84"
PROD_DIR = "/home/xygbfpsg/phingrazuri"

# Files to upload
FILES_TO_DEPLOY = [
    "expenses/views.py",
    "templates/expenses/expenses_list.html",
    "templates/expenses/expense_detail.html",
]

def print_header(text):
    print("\n" + "="*80)
    print(f"  {text}")
    print("="*80)

def run_command(cmd, description):
    """Run a command and handle errors"""
    print(f"\n{description}...")
    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"❌ Error: {result.stderr}")
        return False
    print(f"✅ {description} - Done")
    if result.stdout:
        print(result.stdout)
    return True

def main():
    print_header("DEPLOY EXPENSE EDIT IMPROVEMENTS TO PRODUCTION")
    print(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Production: {PROD_HOST}:{PROD_DIR}")
    
    # Verify files exist
    print("\n📋 Verifying files...")
    missing_files = []
    for file in FILES_TO_DEPLOY:
        if not os.path.exists(file):
            missing_files.append(file)
            print(f"❌ Missing: {file}")
        else:
            print(f"✅ Found: {file}")
    
    if missing_files:
        print(f"\n❌ Cannot deploy - {len(missing_files)} file(s) missing")
        return 1
    
    # Upload files
    print_header("UPLOADING FILES TO PRODUCTION")
    
    for file in FILES_TO_DEPLOY:
        # Create remote directory if needed
        remote_dir = f"{PROD_DIR}/{os.path.dirname(file)}"
        cmd = f'ssh {PROD_HOST} "mkdir -p {remote_dir}"'
        if not run_command(cmd, f"Creating remote directory for {file}"):
            return 1
        
        # Upload file
        remote_path = f"{PROD_DIR}/{file}"
        cmd = f'scp "{file}" {PROD_HOST}:{remote_path}'
        if not run_command(cmd, f"Uploading {file}"):
            return 1
    
    print_header("DEPLOYMENT SUMMARY")
    print(f"✅ Successfully deployed {len(FILES_TO_DEPLOY)} files")
    print("\nChanges deployed:")
    print("  • Updated expenses/views.py - Allow admins/team_leaders to edit any expense")
    print("  • Updated expenses_list.html - Show Edit button for all expenses (admin/team_leader)")
    print("  • Updated expense_detail.html - Show Edit button for all expenses (admin/team_leader)")
    
    print("\n🔄 Restart the application on production to apply changes:")
    print(f"   ssh {PROD_HOST}")
    print(f"   cd {PROD_DIR}")
    print("   touch tmp/restart.txt")
    
    print("\n✅ Deployment complete!")
    return 0

if __name__ == '__main__':
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("\n\n❌ Deployment cancelled by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
