#!/usr/bin/env python3
import os
import sys
import json
import platform
import subprocess
from pathlib import Path

MCP_SERVER_NAME = "kalaasetu"

def get_config_path():
    """Locate the mcp_config.json file across platforms."""
    # Standard path
    config_path = Path.home() / ".gemini" / "antigravity" / "mcp_config.json"
    
    if platform.system() == "Windows":
        # Fallback for Windows if HOME is not set or weird
        user_profile = os.environ.get("USERPROFILE")
        if user_profile:
            win_path = Path(user_profile) / ".gemini" / "antigravity" / "mcp_config.json"
            if win_path.exists():
                return win_path
    
    return config_path

def get_cwd():
    """Get the current working directory in the appropriate format."""
    cwd = os.getcwd()
    if platform.system() == "Windows":
        # Try to use windows-style paths even in MINGW
        return cwd.replace("/", "\\")
    return cwd

def normalize_path(path_str):
    """Normalize path for comparison."""
    if not path_str:
        return ""
    p = Path(os.path.expanduser(path_str)).resolve()
    return str(p)

def load_config(config_path):
    if not config_path.exists():
        print(f"❌ Error: MCP config file not found at {config_path}")
        sys.exit(1)
    
    try:
        with open(config_path, "r") as f:
            return json.load(f)
    except Exception as e:
        print(f"❌ Error reading config: {e}")
        sys.exit(1)

def save_config(config_path, config):
    try:
        with open(config_path, "w") as f:
            json.dump(config, f, indent=2)
    except Exception as e:
        print(f"❌ Error writing config: {e}")
        sys.exit(1)

def set_cwd(verbose=False):
    config_path = get_config_path()
    config = load_config(config_path)
    
    if "mcpServers" not in config or MCP_SERVER_NAME not in config["mcpServers"]:
        print(f"❌ Error: MCP server '{MCP_SERVER_NAME}' not found in config")
        print("Available servers:", ", ".join(config.get("mcpServers", {}).keys()))
        sys.exit(1)
        
    current_cwd = get_cwd()
    current_cwd_norm = normalize_path(current_cwd)
    
    server_config = config["mcpServers"][MCP_SERVER_NAME]
    env = server_config.get("env", {})
    active_folder = env.get("VSCODE_CWD")
    
    if active_folder:
        active_norm = normalize_path(active_folder)
        if current_cwd_norm == active_norm:
            print(f"✅ VSCODE_CWD already set to current directory. No changes needed.")
            return

        print(f"⚠️  WARNING: CONFLICT DETECTED!")
        print(f"   About to switch from: {active_folder}")
        print(f"   To: {current_cwd}")
        print("\n   Since MCP servers are global, only ONE project can use KalaaSetu at a time.")
        
        choice = input("\n   Continue? [y/N] ").lower()
        if choice != 'y':
            print(f"❌ Cancelled. VSCODE_CWD remains: {active_folder}")
            return
    else:
        print(f"➕ Adding VSCODE_CWD to {MCP_SERVER_NAME} (first time setup)")

    if "env" not in server_config:
        server_config["env"] = {}
    
    server_config["env"]["VSCODE_CWD"] = current_cwd
    save_config(config_path, config)
    
    print(f"✅ Success! VSCODE_CWD has been set for {MCP_SERVER_NAME}")
    print("\n📋 To apply changes, restart the antigravity/Gemini CLI session.")

def check_status(verbose=False):
    config_path = get_config_path()
    config = load_config(config_path)
    
    print("📡 KalaaSetu MCP Status Check")
    print("===============================\n")
    
    if "mcpServers" not in config or MCP_SERVER_NAME not in config["mcpServers"]:
        print(f"❌ MCP server '{MCP_SERVER_NAME}' not found in config")
        sys.exit(1)
        
    env = config["mcpServers"][MCP_SERVER_NAME].get("env", {})
    active_folder = env.get("VSCODE_CWD")
    
    if active_folder:
        print(f"✅ VSCODE_CWD is ACTIVE\n\n📂 Active folder:\n   {active_folder}\n")
        
        if os.path.isdir(os.path.expanduser(active_folder)):
            print("✅ Folder exists on disk")
        else:
            print("⚠️  Folder NO LONGER EXISTS on disk")
            
        current_norm = normalize_path(os.getcwd())
        active_norm = normalize_path(active_folder)
        
        if current_norm == active_norm:
            print("\n🎯 You are currently IN the active folder ✅")
        else:
            print(f"\n⚠️  You are in a DIFFERENT folder:\n   📂 {os.getcwd()}")
            print("\n   Run: python3 commands/mcp_manager.py set-cwd\n   to switch to this folder")
    else:
        print("❌ VSCODE_CWD is NOT SET")
        print("\n   Run: python3 commands/mcp_manager.py set-cwd\n   to set current folder as active")
    
    if verbose or True: # Providing config info by default
        print("\nConfig details:")
        print(json.dumps(env, indent=2))

def main():
    import argparse
    parser = argparse.ArgumentParser(description="Manage KalaaSetu MCP configuration")
    parser.add_argument("command", choices=["set-cwd", "status"], help="Command to run")
    parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output")
    
    args = parser.parse_args()
    
    if args.command == "set-cwd":
        set_cwd(args.verbose)
    elif args.command == "status":
        check_status(args.verbose)

if __name__ == "__main__":
    main()
