import api from '../core/api';

export type AskDrAiReference = {
  title?: string;
  url?: string;
};

export type AskDrAiAnswer = {
  title: string;
  answer: string;
  detailed_information?: string;
  layman_term?: string;
  possible_causes?: string[];
  treatment_overview?: string[];
  medical_scientific_name?: string;
  basic_treatment_steps?: string[];
  first_aid_steps?: string[];
  symptoms?: string[];
  references?: AskDrAiReference[];
  source_url?: string;
  fit_percentage: number;
  source?: string;
  source_label?: string;
  matched_terms?: string[];
  document_display?: DocumentDisplay;
  not_found?: boolean;
  category?: string;
  category_label?: string;
};

export type DocumentDisplay = {
  summary?: string;
  formatted_text?: string;
  sections?: Array<{
    title?: string;
    type?: 'fields' | 'table' | 'paragraphs';
    rows?: Array<Record<string, string>>;
    columns?: Array<{ key?: string; label?: string }>;
    paragraphs?: string[];
  }>;
};

export type UploadedFileContextItem = {
  url: string;
  filename: string;
  status: string;
  excerpt?: string;
  message?: string;
  char_count?: number;
  display?: DocumentDisplay;
};

export type AskDrAiPayload = {
  question: string;
  symptoms?: string[];
  uploaded_files?: string[];
  providers?: ('database' | 'global_search' | 'ai')[];
};

export function displayAskDrAiText(value: unknown): string {
  const text = String(value ?? '').trim();
  return text !== '' ? text : 'N/A';
}

export function hasAskDrAiSourceUrl(value: unknown): boolean {
  const url = String(value ?? '').trim();
  return url !== '' && url !== 'N/A';
}

export function isAskDrAiNotFoundAnswer(item: Pick<AskDrAiAnswer, 'title' | 'not_found'>): boolean {
  if (item.not_found === true) {
    return true;
  }

  return String(item.title || '').trim().toLowerCase() === 'sickness/disease not found';
}

function mapScalarField(value: unknown): string {
  const text = String(value ?? '').trim();
  return text !== '' ? text : 'N/A';
}

function mapStringList(value: unknown): string[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((entry) => String(entry ?? '').trim())
    .filter((entry) => entry !== '' && entry !== 'N/A');
}

function mapReferences(value: unknown): AskDrAiReference[] {
  if (!Array.isArray(value)) {
    return [];
  }

  const references: AskDrAiReference[] = [];

  for (const entry of value) {
    if (!entry || typeof entry !== 'object') {
      continue;
    }
    const url = String((entry as AskDrAiReference).url ?? '').trim();
    if (!url) {
      continue;
    }
    const title = String((entry as AskDrAiReference).title ?? '').trim();
    references.push({ title: title || url, url });
  }

  return references;
}

function mapAnswer(item: Record<string, unknown>): AskDrAiAnswer {
  const sourceUrl = String(item.source_url ?? '').trim();

  return {
    title: String(item.title || 'Possible interpretation'),
    answer: mapScalarField(item.answer),
    detailed_information: mapScalarField(item.detailed_information),
    layman_term: mapScalarField(item.layman_term),
    possible_causes: mapStringList(item.possible_causes),
    treatment_overview: mapStringList(item.treatment_overview),
    medical_scientific_name: mapScalarField(item.medical_scientific_name),
    basic_treatment_steps: mapStringList(item.basic_treatment_steps),
    first_aid_steps: mapStringList(item.first_aid_steps),
    symptoms: mapStringList(item.symptoms),
    references: mapReferences(item.references),
    source_url: sourceUrl !== '' && sourceUrl !== 'N/A' ? sourceUrl : '',
    fit_percentage: Number(item.fit_percentage || 0),
    source: String(item.source || 'database'),
    source_label: mapScalarField(item.source_label),
    matched_terms: mapStringList(item.matched_terms),
    document_display: item.document_display as DocumentDisplay | undefined,
    not_found: item.not_found === true,
    category: String(item.category || ''),
    category_label: String(item.category_label || ''),
  };
}

export async function askDrAi(payload: AskDrAiPayload): Promise<{
  answers: AskDrAiAnswer[];
  uploaded_file_context: UploadedFileContextItem[];
  has_extracted_upload_content: boolean;
}> {
  const { data } = await api.post<{
    answers?: Record<string, unknown>[];
    uploaded_file_context?: UploadedFileContextItem[];
    has_extracted_upload_content?: boolean;
  }>('/ask-dr-ai', {
    question: payload.question,
    symptoms: payload.symptoms || [],
    uploaded_files: payload.uploaded_files || [],
    providers: payload.providers || ['database', 'global_search', 'ai'],
  }, {
    timeout: 120000,
  });

  const answers = Array.isArray(data?.answers) ? data.answers.map(mapAnswer) : [];

  return {
    answers,
    uploaded_file_context: Array.isArray(data?.uploaded_file_context) ? data.uploaded_file_context : [],
    has_extracted_upload_content: Boolean(data?.has_extracted_upload_content),
  };
}
