// Cliente para a Tribunal API (scraping em tempo real)

const TRIBUNAL_API_URL = process.env.TRIBUNAL_API_URL || 'http://localhost:3200';

interface TribunalMovimento {
  data: string;
  descricao: string;
}

interface TribunalProcesso {
  numeroProcesso: string;
  tribunal: string;
  classe?: string;
  assunto?: string;
  vara?: string;
  comarca?: string;
  status?: string;
  dataDistribuicao?: string;
  partes?: Array<{ tipo?: string; nome?: string; texto?: string }>;
  movimentos?: TribunalMovimento[];
  ultimaAtualizacao: string;
}

interface TribunalError {
  erro: string;
  codigo: string;
  detalhes?: string;
}

type TribunalResponse = TribunalProcesso | TribunalError;

function isError(response: TribunalResponse): response is TribunalError {
  return 'erro' in response;
}

export async function buscarProcessoTribunal(numero: string): Promise<TribunalResponse> {
  try {
    const response = await fetch(`${TRIBUNAL_API_URL}/api/processo/${encodeURIComponent(numero)}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
      },
      // Timeout de 60s para scraping
      signal: AbortSignal.timeout(60000),
    });

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('[TribunalClient] Erro:', error);
    return {
      erro: 'Erro ao conectar com a Tribunal API',
      codigo: 'CONEXAO_ERRO',
      detalhes: error instanceof Error ? error.message : 'Erro desconhecido'
    };
  }
}

export async function listarTribunaisSuportados(): Promise<string[]> {
  try {
    const response = await fetch(`${TRIBUNAL_API_URL}/api/tribunais`);
    const data = await response.json();
    return data.tribunais?.map((t: { codigo: string }) => t.codigo) || [];
  } catch {
    return [];
  }
}

export async function healthCheck(): Promise<boolean> {
  try {
    const response = await fetch(`${TRIBUNAL_API_URL}/api/health`);
    const data = await response.json();
    return data.status === 'ok';
  } catch {
    return false;
  }
}

export { isError, type TribunalProcesso, type TribunalError, type TribunalResponse };
