#!/usr/bin/env python3
"""
Cortex Agent Node - Daemon Installer
====================================
Configures the Cortex Agent to run automatically as a background daemon
using platform-specific abstractions.

Usage:
    python3 install_service.py
"""

import os
import sys
import platform

# Ensure the agent_node package can be found if we're running from the root of the distribution
_src_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "src"))
if os.path.exists(_src_path):
    sys.path.insert(0, _src_path)

from agent_node.utils.service_manager import get_service_manager

def get_python_path():
    return sys.executable

def get_agent_main_path():
    # Use absolute path to the main.py entry point
    return os.path.abspath(os.path.join(os.path.dirname(__file__), "src", "agent_node", "main.py"))

def get_working_dir():
    return os.path.abspath(os.path.dirname(__file__))

def main():
    agent_path = get_agent_main_path()
    if not os.path.exists(agent_path):
        print(f"❌ Error: Could not find main agent script at {agent_path}")
        sys.exit(1)

    print(f"[*] Detected Platform: {platform.system()}")
    manager = get_service_manager()
    
    python_exe = get_python_path()
    working_dir = get_working_dir()
    
    print(f"[*] Installing service: {python_exe} {agent_path}")
    if manager.install(python_exe, agent_path, working_dir):
        print("✅ Agent service/daemon successfully installed and started!")
    else:
        print("❌ Failed to install service automatically.")
        if platform.system() != "Windows":
             print("Try running with higher privileges or check system logs.")
        else:
             print("Please ensure you are running as an Administrator.")

if __name__ == "__main__":
    main()
