import * as didUtils from './dids/utils.js';

/**
 * Dynamically selects DWN endpoints
 */
export async function getServiceDwnEndpoints(): Promise<string[]> {
  let response: Response;
  try {
    response = await fetch('https://s3.amazonaws.com/dwn.id/.well-known/did.json', {
      method  : 'GET',
      mode    : 'cors',
      cache   : 'no-cache',
      headers : {
        'Accept'       : '*/*',
        'Content-Type' : 'application/json',
      },
    });
    // console.log('response', response);
    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status} ${response.statusText}`);
    }
  } catch(error: any) {
    // console.warn('failed to get dwn endpoints:', error.message);
    return [];
  }

  const didDocument = await response.json();
  const [ dwnService ] = didUtils.getServices({ didDocument, id: '#dwn', type: 'DecentralizedWebNode' });

  // allocate nodes for a user.
  const dwnEndpoints = new Set<string>();

  if ('serviceEndpoint' in dwnService
      && !Array.isArray(dwnService.serviceEndpoint)
      && typeof dwnService.serviceEndpoint !== 'string'
      && Array.isArray(dwnService.serviceEndpoint.nodes)) {
    const dwnUrls = dwnService.serviceEndpoint.nodes;

    const numNodesToAllocate = Math.min(dwnUrls.length, 3);
    for (let attempts = 0; attempts < dwnUrls.length && dwnEndpoints.size <= numNodesToAllocate; attempts += 1) {
      // when we have more relayers we can dynamically choose up to 3
      // const nodeIdx = getRandomInt(0, dwnUrls.length);
      const dwnUrl = dwnUrls[attempts];
      try {
        const healthCheck = await fetch(`${dwnUrl}/health`);
        if (healthCheck.ok) {
          dwnEndpoints.add(dwnUrl);
        }
      } catch(error: unknown) {
        // Ignore healthcheck failure and try the next node.
      }
    }
  }

  return Array.from(dwnEndpoints);
}

// function getRandomInt(min, max) {
//   min = Math.ceil(min);
//   max = Math.floor(max);
//   return Math.floor(Math.random() * (max - min)) + min;
// }