#!/usr/bin/env node

/**
 * MCP Server for Omada Controller
 * 
 * Entry point for the Model Context Protocol server that provides
 * tools for managing TP-Link Omada devices (ER605, SG218R, etc.)
 */

import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { homedir } from 'os';
import { OmadaServer } from './server/OmadaServer.js';

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

// Load environment variables from ~/.env file (standardized location)
const envPath = join(homedir(), '.env');
const envPathFallback = join(__dirname, '../.env');

function loadEnvFile(filePath: string): boolean {
  try {
    const envFile = readFileSync(filePath, 'utf8');
    const envVars = envFile.split('\n').filter(
      (line) => line.includes('=') && !line.trim().startsWith('#')
    );
    for (const line of envVars) {
      const [key, ...values] = line.split('=');
      // Validate key is a valid environment variable name
      if (key && values.length > 0 && /^[A-Z_][A-Z0-9_]*$/.test(key.trim())) {
        // Remove surrounding quotes if present and trim
        let value = values.join('=').trim();
        if (
          (value.startsWith('"') && value.endsWith('"')) ||
          (value.startsWith("'") && value.endsWith("'"))
        ) {
          value = value.slice(1, -1);
        }
        process.env[key.trim()] = value;
      }
    }
    return true;
  } catch (error) {
    return false;
  }
}

// Try ~/.env first, then fallback to relative path
if (!loadEnvFile(envPath)) {
  if (!loadEnvFile(envPathFallback)) {
    console.error('Warning: Could not load .env file from ~/.env or ../.env');
  }
}

// Get configuration from environment variables
const baseUrl =
  process.env.OMADA_CONTROLLER_URL || 'https://192.168.11.8:8043';
const clientId = process.env.OMADA_API_KEY || '';
const clientSecret = process.env.OMADA_API_SECRET || '';
const siteId = process.env.OMADA_SITE_ID;
const verifySSL = process.env.OMADA_VERIFY_SSL !== 'false';

if (!clientId || !clientSecret) {
  console.error(
    'Error: OMADA_API_KEY and OMADA_API_SECRET must be set in environment variables'
  );
  process.exit(1);
}

// Create and run the server
const server = new OmadaServer({
  baseUrl,
  clientId,
  clientSecret,
  siteId,
  verifySSL,
});

server.run().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});

