"""
Workspace Agent — Main Entrypoint

Standalone tool execution engine.
Connects to AWS backend via WSS, executes tools locally.
"""

import argparse
import asyncio
import logging
import os
import sys
import signal
from pathlib import Path

from . import __version__
from .connection import WorkspaceConnection
from .credential_vault import CredentialVault
from .executor import ToolExecutor
from .audit import AuditLogger

logger = logging.getLogger("workspace-agent")


def setup_logging(level: str = "INFO"):
    """Configure structured logging."""
    # Force UTF-8 on Windows to support emoji/unicode in logs
    if sys.platform == "win32":
        import io
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
        sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")

    logging.basicConfig(
        level=getattr(logging, level.upper(), logging.INFO),
        format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        stream=sys.stdout,
    )
    # Quiet noisy libraries
    logging.getLogger("websockets").setLevel(logging.WARNING)
    logging.getLogger("httpx").setLevel(logging.WARNING)
    logging.getLogger("httpcore").setLevel(logging.WARNING)


def parse_args():
    parser = argparse.ArgumentParser(description="DataTrader Workspace Agent")
    parser.add_argument("--server", default=os.environ.get("SERVER", "ws://localhost:8000"),
                        help="WSS server URL (e.g., wss://api.example.com)")
    parser.add_argument("--token", default=os.environ.get("TOKEN"),
                        help="Authentication token")
    parser.add_argument("--workspace", default=os.environ.get("WORKSPACE_PATH", "/workspace"),
                        help="Workspace directory path")
    parser.add_argument("--vault-dir", default=os.environ.get("VAULT_DIR"),
                        help="Credential vault directory (default: <workspace>/.vault)")
    parser.add_argument("--log-level", default=os.environ.get("LOG_LEVEL", "INFO"),
                        help="Log level (DEBUG, INFO, WARNING, ERROR)")
    parser.add_argument("--audit-level", default=os.environ.get("AUDIT_LEVEL", "full"),
                        help="Audit log level (full, summary, errors_only)")
    parser.add_argument("--self-test", action="store_true",
                        help="Run self-test and exit")
    return parser.parse_args()


def main():
    args = parse_args()
    setup_logging(args.log_level)

    # Banner
    logger.info("=" * 60)
    logger.info(f"  DataTrader Workspace Agent v{__version__}")
    logger.info(f"  Workspace: {args.workspace}")
    logger.info(f"  Server: {args.server}")
    logger.info(f"  Python: {sys.version.split()[0]}")
    logger.info(f"  Platform: {sys.platform}")
    logger.info("=" * 60)

    # Validate token
    if not args.token and not args.self_test:
        logger.error("❌ TOKEN is required. Pass --token or set TOKEN env var.")
        logger.error("   Generate a token at: https://app.darrxscale.com/workspaces")
        sys.exit(1)

    workspace_path = os.path.abspath(args.workspace)
    if not os.path.isdir(workspace_path):
        logger.warning(f"Workspace directory does not exist, creating: {workspace_path}")
        os.makedirs(workspace_path, exist_ok=True)

    # Initialize components
    vault_dir = args.vault_dir or os.path.join(workspace_path, ".vault")
    vault = CredentialVault(vault_dir, encryption_key=args.token or "self-test-key")
    audit = AuditLogger(log_level=args.audit_level)
    executor = ToolExecutor(workspace_path, vault, audit)

    # Self-test mode
    if args.self_test:
        return _run_self_test(executor, vault)

    # Tool request handler
    def handle_tool_request(request):
        return executor.execute(request)

    # Create connection
    connection = WorkspaceConnection(
        server_url=args.server,
        token=args.token,
        version=__version__,
        on_tool_request=handle_tool_request,
        vault=vault,
    )

    # Run with proper signal handling
    audit.log_connection("starting", {"version": __version__, "workspace": workspace_path})

    try:
        if sys.platform == "win32":
            # Windows: use ProactorEventLoop for subprocess support
            asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
        
        asyncio.run(_run_with_signals(connection))
    except KeyboardInterrupt:
        logger.info("Interrupted by user")
    finally:
        executor.close()
        audit.log_connection("stopped")
        logger.info("Workspace agent stopped")


async def _run_with_signals(connection: WorkspaceConnection):
    """Run connection with proper signal handling on all platforms."""
    loop = asyncio.get_running_loop()
    
    if sys.platform != "win32":
        # Unix: use signal handlers
        for sig in (signal.SIGTERM, signal.SIGINT):
            loop.add_signal_handler(sig, lambda: asyncio.create_task(connection.stop()))
    
    await connection.run()


def _run_self_test(executor: ToolExecutor, vault: CredentialVault) -> None:
    """Run self-test and exit."""
    logger.info("\n🔍 Running self-test...\n")
    
    ok = executor.self_test()
    
    creds = vault.list_services()
    logger.info(f"\n📦 Vault: {len(creds)} credential(s) stored")
    
    tool_list = executor.get_tool_list()
    logger.info(f"🔧 Tools loaded: {len(tool_list)}")
    for t in tool_list:
        logger.info(f"   • {t['name']}: {t['description'][:60]}")
    
    logger.info(f"\n{'✅ All tests passed' if ok else '❌ Some tests failed'}")
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
