#!/usr/bin/env python3
"""
Post-installation script for NC1709
Ensures CLI commands are accessible by setting up PATH
"""

import os
import sys
import platform
import subprocess
from pathlib import Path


def get_shell_profile_path():
    """Get the appropriate shell profile file"""
    home = Path.home()
    
    # Check which shell is being used
    shell = os.environ.get('SHELL', '')
    
    if 'zsh' in shell:
        return home / '.zshrc'
    elif 'fish' in shell:
        return home / '.config/fish/config.fish'
    elif 'bash' in shell:
        return home / '.bashrc'
    else:
        # Default to .profile which works across shells
        return home / '.profile'


def add_to_path():
    """Add ~/.local/bin to PATH if not already present"""
    local_bin = str(Path.home() / '.local/bin')
    
    # Check if already in PATH
    current_path = os.environ.get('PATH', '')
    if local_bin in current_path.split(os.pathsep):
        print(f"✅ {local_bin} already in PATH")
        return True
    
    # Add to shell profile
    profile_path = get_shell_profile_path()
    path_line = f'export PATH="$PATH:{local_bin}"\n'
    
    try:
        # Check if line already exists
        if profile_path.exists():
            content = profile_path.read_text()
            if local_bin in content:
                print(f"✅ PATH already configured in {profile_path}")
                return True
        
        # Append to profile
        with open(profile_path, 'a') as f:
            f.write(f'\n# Added by NC1709\n{path_line}')
        
        print(f"✅ Added {local_bin} to PATH in {profile_path}")
        print(f"📝 Restart your terminal or run: source {profile_path}")
        return True
        
    except Exception as e:
        print(f"❌ Could not modify {profile_path}: {e}")
        print(f"💡 Please manually add this to your shell profile:")
        print(f"   export PATH=\"$PATH:{local_bin}\"")
        return False


def check_installation():
    """Check if NC1709 commands are accessible"""
    local_bin = Path.home() / '.local/bin'
    nc1709_cmd = local_bin / 'nc1709'
    
    if nc1709_cmd.exists():
        print(f"✅ NC1709 installed at {nc1709_cmd}")
        
        # Test if command is in PATH
        try:
            subprocess.run(['nc1709', '--version'], 
                          capture_output=True, check=True)
            print("✅ NC1709 commands accessible via PATH")
            return True
        except (subprocess.CalledProcessError, FileNotFoundError):
            print("⚠️  NC1709 installed but not in PATH")
            return False
    else:
        print("❌ NC1709 not found in expected location")
        return False


def main():
    """Main post-install setup"""
    print("🚀 Setting up NC1709...")
    
    if platform.system() == 'Windows':
        print("ℹ️  Windows detected - PATH setup may require manual configuration")
        return
    
    # Check current installation
    if check_installation():
        print("🎉 NC1709 is ready to use!")
        return
    
    # Try to add to PATH
    if add_to_path():
        print("\n🎉 NC1709 setup complete!")
        print("📋 Available commands:")
        print("   - nc1709           # Main CLI")
        print("   - nc1709-enhanced  # Enhanced features") 
        print("   - nc1709-benchmark # Performance testing")
    else:
        print("\n⚠️  Manual PATH setup required")


if __name__ == "__main__":
    main()