import type { Handler, HandlerEvent } from "@netlify/functions";
import { AccessToken } from 'livekit-server-sdk';
import type { VideoGrant } from 'livekit-server-sdk';

const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || '';
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET || '';
const LIVEKIT_URL = process.env.LIVEKIT_URL || process.env.LIVEKIT_SERVER_URL || '';
const AGENT_IDENTITY = process.env.AGENT_IDENTITY || 'ml-agent';

const handler: Handler = async (event: HandlerEvent) => {
  console.log('Token request received with params:', {
    room: event.queryStringParameters?.room,
    identity: event.queryStringParameters?.identity,
    language: event.queryStringParameters?.language,
    hasEmail: !!event.queryStringParameters?.email,
    hasName: !!event.queryStringParameters?.name,
  });

  // Check environment variables
  const envStatus = {
    hasApiKey: !!LIVEKIT_API_KEY,
    hasApiSecret: !!LIVEKIT_API_SECRET,
    hasUrl: !!LIVEKIT_URL,
    urlProtocol: LIVEKIT_URL ? LIVEKIT_URL.split('://')[0] : 'none'
  };
  
  console.log('Environment status:', envStatus);

  if (!LIVEKIT_API_KEY || !LIVEKIT_API_SECRET || !LIVEKIT_URL) {
    console.error('Missing required environment variables');
    return {
      statusCode: 500,
      body: JSON.stringify({ 
        error: "Server is not configured correctly.",
        details: `Missing: ${!LIVEKIT_API_KEY ? 'API_KEY ' : ''}${!LIVEKIT_API_SECRET ? 'API_SECRET ' : ''}${!LIVEKIT_URL ? 'URL' : ''}`.trim()
      }),
    };
  }

  const { room, identity, name, email, language, timezone } = event.queryStringParameters || {};

  if (!room || !identity) {
    console.error('Missing required parameters:', { hasRoom: !!room, hasIdentity: !!identity });
    return {
      statusCode: 400,
      body: JSON.stringify({ error: "Missing 'room' or 'identity' query parameters" }),
    };
  }

  const grant: VideoGrant = {
    room,
    roomJoin: true,
    canPublish: true,
    canPublishData: true,
    canSubscribe: true,
    // Allow participants to update their own metadata which can help the agent and UI
    canUpdateOwnMetadata: true,
  };

  try {
    console.log('Attempting to generate token with:', {
      hasIdentity: !!identity,
      hasRoom: !!room,
      metadata: { hasName: !!name, hasEmail: !!email, language, timezone }
    });

    const metadata = JSON.stringify({ name, email, language, timezone, role: 'user' });
    
    console.log('Creating AccessToken with API key length:', LIVEKIT_API_KEY.length);
    const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { identity, metadata });
    
    console.log('Adding grant:', grant);
    at.addGrant(grant);

    // Generate the JWT token string
    console.log('Generating JWT...');
    const tokenString = await Promise.resolve(at.toJwt());
    
    // Log token info without exposing the full token
    const tokenInfo = {
      length: typeof tokenString === 'string' ? tokenString.length : 0,
      isString: typeof tokenString === 'string',
      startsWithEy: typeof tokenString === 'string' && tokenString.startsWith('ey'),
      preview: typeof tokenString === 'string' ? `${tokenString.slice(0, 3)}...` : 'null'
    };
    console.log('Token generated:', tokenInfo);
    
    // Verify we have a valid token string
    if (typeof tokenString !== 'string' || !tokenString) {
      console.error('Token validation failed:', {
        type: typeof tokenString,
        isNull: tokenString === null,
        isUndefined: tokenString === undefined
      });
      throw new Error('Failed to generate token string');
    }

    // Normalize LIVEKIT_URL: ensure it's provided and return both `url` and `serverUrl` for compatibility
    if (!LIVEKIT_URL.startsWith('ws://') && !LIVEKIT_URL.startsWith('wss://')) {
      console.log('Warning: LIVEKIT_URL should start with ws:// or wss://', { providedUrl: LIVEKIT_URL });
    }

    return {
      statusCode: 200,
      headers: { 
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*", // Enable CORS
        "Access-Control-Allow-Headers": "Content-Type"
      },
      body: JSON.stringify({
        token: tokenString,
        serverUrl: LIVEKIT_URL,
        url: LIVEKIT_URL,
        agentIdentity: AGENT_IDENTITY
      })
    };
  } catch (error) {
    console.error('Error generating token:', error);
    return {
      statusCode: 500,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ 
        error: "Failed to generate token",
        details: error instanceof Error ? error.message : String(error)
      })
    };
  }
};

export { handler };