#!/usr/bin/env node

/**
 * MCP Auth Proxy — entry point.
 *
 * Bridges stdio (Copilot CLI) ↔ HTTP (MCP server) with automatic OAuth token refresh.
 *
 * Required environment variables:
 *   MCP_URL            — MCP server URL (e.g. "https://mcp.ccmqa.com/mcp")
 *   MCP_CLIENT_ID      — OAuth client ID for client_credentials flow
 *   MCP_CLIENT_SECRET   — OAuth client secret
 *
 * Optional:
 *   MCP_REFRESH_BUFFER  — seconds before token expiry to trigger refresh (default: 60)
 */

import { TokenManager } from './token-manager.js';
import { McpProxy } from './mcp-proxy.js';

const log = (msg) => process.stderr.write(`[mcp-proxy] ${msg}\n`);

const MCP_URL = process.env.MCP_URL;
const CLIENT_ID = process.env.MCP_CLIENT_ID;
const CLIENT_SECRET = process.env.MCP_CLIENT_SECRET;
const REFRESH_BUFFER = parseInt(process.env.MCP_REFRESH_BUFFER || '60', 10);

if (!MCP_URL || !CLIENT_ID || !CLIENT_SECRET) {
  process.stderr.write(`Usage: MCP_URL=... MCP_CLIENT_ID=... MCP_CLIENT_SECRET=... node index.js

Required environment variables:
  MCP_URL             MCP server URL (e.g. https://mcp.ccmqa.com/mcp)
  MCP_CLIENT_ID       OAuth client ID
  MCP_CLIENT_SECRET   OAuth client secret

Optional:
  MCP_REFRESH_BUFFER  Seconds before expiry to refresh token (default: 60)
`);
  process.exit(1);
}

async function main() {
  const tokenManager = new TokenManager({
    clientId: CLIENT_ID,
    clientSecret: CLIENT_SECRET,
    refreshBufferSec: REFRESH_BUFFER,
  });

  try {
    await tokenManager.discover(MCP_URL);
  } catch (err) {
    log(`OAuth discovery failed: ${err.message}`);
    process.exit(1);
  }

  // Pre-fetch a token to fail fast if credentials are wrong
  try {
    await tokenManager.getToken();
  } catch (err) {
    log(`Initial token fetch failed: ${err.message}`);
    process.exit(1);
  }

  const proxy = new McpProxy({ mcpUrl: MCP_URL, tokenManager });
  proxy.start();

  log(`Proxy started → ${MCP_URL}`);
}

// Graceful shutdown
process.on('SIGTERM', () => process.exit(0));
process.on('SIGINT', () => process.exit(0));

main().catch((err) => {
  log(`Fatal: ${err.message}`);
  process.exit(1);
});
