#!/usr/bin/env python3
"""Post-installation script for sinhala-mcp.

This script runs automatically after pip install to set up VS Code configuration.
"""

import os
import sys
import json
from pathlib import Path


def setup_vscode_config():
    """Create .vscode/settings.json with sinhala-mcp model sampling config."""

    # Try to find the project root (where .git or pyproject.toml is)
    current_dir = Path.cwd()

    # Look for project root by checking for .git or pyproject.toml
    project_root = current_dir
    for parent in [current_dir] + list(current_dir.parents):
        if (parent / ".git").exists() or (parent / "pyproject.toml").exists():
            project_root = parent
            break

    vscode_dir = project_root / ".vscode"
    settings_file = vscode_dir / "settings.json"

    # Create .vscode directory if it doesn't exist
    try:
        vscode_dir.mkdir(exist_ok=True)
    except Exception:
        # If we can't create in project root, try current directory
        vscode_dir = Path.cwd() / ".vscode"
        settings_file = vscode_dir / "settings.json"
        vscode_dir.mkdir(exist_ok=True)

    # Define the model sampling configuration
    mcp_config = {
        "chat.mcp.serverSampling": {
            "sinhala-mcp/.vscode/mcp.json: sinhala-mcp": {
                "allowedModels": [
                    "copilot/auto",
                    "gemini-2.5-flash",
                    "gemini-2.5-flash-lite",
                    "gemini-2.5-pro",
                    "gemini-1.5-flash",
                ]
            }
        }
    }

    # Read existing settings if they exist
    existing_settings = {}
    if settings_file.exists():
        try:
            with open(settings_file, "r", encoding="utf-8") as f:
                existing_settings = json.load(f)
        except Exception:
            pass

    # Merge configurations
    merged_settings = {**existing_settings, **mcp_config}

    # Write the merged settings
    with open(settings_file, "w", encoding="utf-8") as f:
        json.dump(merged_settings, f, indent=4)

    return True


def main():
    """Main post-installation function."""

    print("\n" + "="*60)
    print("🇱🇰 sinhala-mcp - Post-Installation Setup")
    print("="*60)

    # Run VS Code setup
    try:
        if setup_vscode_config():
            print("✅ VS Code configuration created successfully!")
            print("   Location: .vscode/settings.json")
            print("   Added: Model sampling configuration for sinhala-mcp")
    except Exception as e:
        print(f"⚠️  Could not create VS Code config: {e}")
        print("   You can manually run: python setup_vscode.py")

    print("\n" + "="*60)
    print("✨ sinhala-mcp is ready to use!")
    print("="*60)
    print("\nNext steps:")
    print("1. Set your GEMINI_API_KEY environment variable")
    print("2. Or configure it in your MCP client settings")
    print("\nFor help, visit: https://github.com/Thamindu-Dev/sinhala-mcp")
    print("="*60 + "\n")


if __name__ == "__main__":
    main()
