/**
 * Twilio credential management.
 * Supports: ACCOUNT_SID/API_KEY:API_SECRET format from CLI arg or env vars.
 */

export interface TwilioCredentials {
  accountSid: string;
  apiKey: string;
  apiSecret: string;
}

export function parseCredentials(arg?: string): TwilioCredentials {
  // Try CLI argument first: ACCOUNT_SID/API_KEY:API_SECRET
  if (arg) {
    const match = arg.match(/^(AC[a-f0-9]{32})\/(SK[a-f0-9]{32}):(.+)$/);
    if (match) {
      return { accountSid: match[1], apiKey: match[2], apiSecret: match[3] };
    }
    // Also support ACCOUNT_SID:AUTH_TOKEN format
    const simpleMatch = arg.match(/^(AC[a-f0-9]{32}):(.+)$/);
    if (simpleMatch) {
      return { accountSid: simpleMatch[1], apiKey: simpleMatch[1], apiSecret: simpleMatch[2] };
    }
    throw new Error(
      'Invalid credential format. Expected: ACCOUNT_SID/API_KEY:API_SECRET or ACCOUNT_SID:AUTH_TOKEN'
    );
  }

  // Fall back to environment variables
  const accountSid = process.env.TWILIO_ACCOUNT_SID;
  const apiKey = process.env.TWILIO_API_KEY || process.env.TWILIO_ACCOUNT_SID;
  const apiSecret = process.env.TWILIO_API_SECRET || process.env.TWILIO_AUTH_TOKEN;

  if (!accountSid || !apiSecret) {
    throw new Error(
      'Missing Twilio credentials. Provide as CLI arg (ACCOUNT_SID/API_KEY:API_SECRET) ' +
      'or set TWILIO_ACCOUNT_SID + TWILIO_API_KEY/TWILIO_API_SECRET env vars.'
    );
  }

  return { accountSid, apiKey: apiKey!, apiSecret };
}
