#!/usr/bin/env node

import { Command } from 'commander';
import fs from 'fs';
import path from 'path';
import os from 'os';
import { fileURLToPath } from 'url';
import { startDaemon } from './utils/daemon.js';
import { getConfig, saveConfig } from './utils/config.js';

// --- MCP Imports ---
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { server } from "./mcps/projectMcpServer.js"; 

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

let packageJson = { version: "1.0.15" };
try {
    packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
} catch (e) {
    console.warn("⚠️ Could not read package.json, defaulting version.");
}

const program = new Command();

program
  .name('thrust')
  .description('Thrust Local Agent - Proactive AI Project Director')
  .version(packageJson.version, '-v, --version', 'Output the current version')
  .option('-p, --port <number>', 'Port for the local dashboard', '8765')
  .action(async (options) => {
    console.log('🚀 Booting Thrust Agent...');

    await setupNativeStartup();

    startDaemon(parseInt(options.port, 10));
  });

program
  .command('link <leadId> <folderPath>')
  .description('Link a local folder to a Thrust Project/Lead')
  .action((leadId, folderPath) => {
    const absolutePath = path.resolve(folderPath);

    if (!fs.existsSync(absolutePath)) {
        console.error(`❌ Folder does not exist: ${absolutePath}`);
        process.exit(1);
    }

    const config = getConfig();
    config.leads[leadId] = {
        path: absolutePath,
        linkedAt: new Date().toISOString()
    };
    config.activeLeadId = leadId;

    saveConfig(config);
    console.log(`✅ Successfully linked Lead[${leadId}] to ${absolutePath}`);
    console.log(`Type 'thrust' to begin tracking.`);
  });

// --- NEW MCP COMMAND ---
program
  .command('mcp')
  .description('Start the Thrust MCP Server over Stdio for AI clients (Claude, VS Code, Cursor)')
  .action(async () => {
    try {
        // IMPORTANT: We must use console.error here. 
        // console.log prints to stdout, which corrupts the JSON-RPC stream the AI expects.
        console.error('Starting Thrust MCP Server over Stdio...');
        
        const transport = new StdioServerTransport();
        await server.connect(transport);
        
        console.error('Thrust MCP Server is ready and listening.');
    } catch (error) {
        console.error('MCP Server crashed:', error);
        process.exit(1);
    }
  });

program.parse(process.argv);

// --- NATIVE, CROSS-PLATFORM OS STARTUP LOGIC ---
async function setupNativeStartup() {
    // 1. Termux (Android)
    if (process.env.TERMUX_VERSION) {
        console.log('📱 Termux detected: (Tip: Use the `termux-boot` app for OS startup).');
        return;
    }

    // 2. Windows - Clean, direct global execution
    if (process.platform === 'win32') {
        try {
            const startupFolder = path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
            const batFilePath = path.join(startupFolder, 'thrust-agent.bat');

            // Clean batch script that simply calls the global `thrust` command
            const batContent = `@echo off\ntitle Thrust Local Agent\necho Starting Thrust...\ntimeout /t 2 /nobreak > NUL\nthrust\npause`;

            if (!fs.existsSync(startupFolder)) fs.mkdirSync(startupFolder, { recursive: true });
            fs.writeFileSync(batFilePath, batContent, 'utf8');
            console.log('⚙️ Windows Startup Script active.');
        } catch (err) {
            console.log(`⚠️ Failed to create Windows startup script: ${err.message}`);
        }
    }

    // 3. macOS - Requires absolute paths due to empty launchd $PATH
    else if (process.platform === 'darwin') {
        try {
            const launchAgentsDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
            const plistPath = path.join(launchAgentsDir, 'com.thrust.agent.plist');

            const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.thrust.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>${process.execPath}</string>
        <string>${__filename}</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>`;

            if (!fs.existsSync(launchAgentsDir)) fs.mkdirSync(launchAgentsDir, { recursive: true });
            fs.writeFileSync(plistPath, plistContent, 'utf8');

            import('child_process').then(({ exec }) => {
                exec(`launchctl load -w "${plistPath}"`, () => {});
            });
            console.log('⚙️ macOS LaunchAgent active (Will run silently in background on boot).');
        } catch (err) {
            console.log(`⚠️ Failed to create macOS LaunchAgent: ${err.message}`);
        }
    }

    // 4. Linux - Requires absolute paths for FreeDesktop compliance
    else if (process.platform === 'linux') {
        try {
            if (!process.env.DISPLAY) {
                console.log('🖥️ Headless Linux detected: Skipping GUI Autostart.');
                return;
            }

            const autostartDir = path.join(os.homedir(), '.config', 'autostart');
            const desktopPath = path.join(autostartDir, 'thrust-agent.desktop');

            const desktopContent = `[Desktop Entry]
Type=Application
Exec="${process.execPath}" "${__filename}"
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Thrust Local Agent
Comment=Proactive AI Project Director
Terminal=true`;

            if (!fs.existsSync(autostartDir)) fs.mkdirSync(autostartDir, { recursive: true });
            fs.writeFileSync(desktopPath, desktopContent, 'utf8');
            console.log('⚙️ Linux Autostart active (A terminal will open automatically on next reboot).');
        } catch (err) {
            console.log(`⚠️ Failed to create Linux startup script: ${err.message}`);
        }
    }
}
