#!/usr/bin/env python3
"""Post-install script to setup ReplyMarketing CLI."""
from __future__ import annotations

import shutil
import sys
from pathlib import Path

def postinstall() -> int:
    """Setup ReplyMarketing CLI after installation."""
    home_dir = Path.home()
    target_dir = home_dir / ".replycash" / "skills"
    
    # Find source skills directory
    # When installed, skills should be in package directory
    try:
        import replymarketing
        package_dir = Path(replymarketing.__file__).parent.parent.parent
    except ImportError:
        # Development mode - use current directory
        package_dir = Path.cwd()
    
    source_dir = package_dir / "skills"
    
    print("📦 Setting up ReplyMarketing CLI...")
    print()
    
    try:
        # Create directories
        target_dir.mkdir(parents=True, exist_ok=True)
        
        # Check if source skills exist
        if not source_dir.exists():
            print("⚠️  Bundled skills not found, will download on first run")
            return 0
        
        # Copy bundled skills
        _copy_directory(source_dir, target_dir)
        print(f"✅ Skills installed to ~/.replycash/skills/")
        
        # Create default config
        config_dir = home_dir / ".config" / "replycash"
        config_path = config_dir / "config.json"
        
        config_dir.mkdir(parents=True, exist_ok=True)
        
        if not config_path.exists():
            import json
            from datetime import datetime
            
            default_config = {
                "version": "1.0.0",
                "provider": None,
                "skills": {
                    "auto_update": True,
                    "last_update": datetime.now().isoformat()
                },
                "preferences": {
                    "confirm_before_submit": True
                }
            }
            
            with open(config_path, "w") as f:
                json.dump(default_config, f, indent=2)
            
            print("✅ Config created at ~/.config/replycash/config.json")
            print("✅ Credentials will be stored at ~/.config/replycash/credentials.json")
        
        print()
        print("🎉 Setup complete! Run `replymarketing` to start.")
        print()
        
        return 0
        
    except Exception as e:
        print(f"❌ Setup failed: {e}")
        return 1


def _copy_directory(src: Path, dest: Path) -> None:
    """Copy directory recursively."""
    if not dest.exists():
        dest.mkdir(parents=True, exist_ok=True)
    
    for item in src.iterdir():
        dest_item = dest / item.name
        
        if item.is_dir():
            _copy_directory(item, dest_item)
        else:
            try:
                shutil.copy2(item, dest_item)
            except Exception:
                print(f"⚠️  Could not copy {item.name}")


if __name__ == "__main__":
    sys.exit(postinstall())
