import type { DocInfo, DocListResponse, DocUploadResponse } from './index';
import { API_BASE_URL } from './index';

const TOKEN_KEY = 'auth_token';
function authHeaders(extra?: Record<string, string>): Record<string, string> {
  const token = localStorage.getItem(TOKEN_KEY);
  return token ? { Authorization: `Bearer ${token}`, ...extra } : { ...extra };
}

interface BackendDocumentItem {
  doc_id: string;
  doc_name: string;
  status: string;
  chunk_count: number;
  size_bytes?: number;
  summary?: string;
  updated_at?: string;
  regulation_type?: string;
  version?: string;
}

interface BackendDocumentListResponse {
  documents: BackendDocumentItem[];
  total: number;
  limit?: number;
}

interface BackendKnowledgeResult {
  id: number;
  content: string;
  score: number;
  metadata: Record<string, unknown>;
}

interface BackendKnowledgeResponse {
  query: string;
  total: number;
  results: BackendKnowledgeResult[];
}

export interface RegulationSearchItem {
  id: number;
  file: string;
  clause: string;
  score: number;
  content: string;
  tags: string[];
}

export interface RegulationSearchResponse {
  query: string;
  total: number;
  results: RegulationSearchItem[];
}

function mapDoc(item: BackendDocumentItem): DocInfo {
  const sizeMB = item.size_bytes ? (item.size_bytes / (1024 * 1024)).toFixed(1) + 'MB' : '';
  return {
    id: item.doc_id,
    name: item.doc_name,
    chunks: item.chunk_count,
    status: item.status,
    updated_at: item.updated_at,
    download_url: `${API_BASE_URL}/documents/download/${item.doc_id}`,
    size_text: sizeMB,
    summary: item.summary,
    regulation_type: item.regulation_type,
    version: item.version,
  };
}

export async function uploadDocument(
  file: File,
  opts?: { regulationType?: string; version?: string }
): Promise<DocUploadResponse> {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('doc_name', file.name);
  formData.append('generate_summary', 'true');
  if (opts?.regulationType) formData.append('regulation_type', opts.regulationType);
  if (opts?.version) formData.append('version', opts.version);

  const response = await fetch(`${API_BASE_URL}/documents/upload`, {
    method: 'POST',
    headers: authHeaders(),
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }

  const data = (await response.json()) as DocUploadResponse;
  return {
    doc_id: data.doc_id,
    doc_name: data.doc_name || file.name,
    status: data.status,
    message: data.message,
    num_chunks: data.num_chunks,
    summary: data.summary,
  };
}

export async function getDocumentList(): Promise<DocListResponse> {
  const response = await fetch(`${API_BASE_URL}/documents/management-list`, {
    headers: authHeaders(),
  });
  if (!response.ok) {
    throw new Error(`List failed: ${response.status}`);
  }

  const data = (await response.json()) as BackendDocumentListResponse;
  return {
    docs: data.documents.map(mapDoc),
  };
}

export async function getDocumentStatus(docId: string): Promise<DocUploadResponse> {
  const response = await fetch(`${API_BASE_URL}/documents/status/${docId}`, {
    headers: authHeaders(),
  });
  if (!response.ok) {
    throw new Error(`Status check failed: ${response.status}`);
  }
  return response.json() as Promise<DocUploadResponse>;
}

export async function deleteDocument(docId: string): Promise<void> {
  const response = await fetch(`${API_BASE_URL}/documents/${docId}`, {
    method: 'DELETE',
    headers: authHeaders(),
  });
  if (!response.ok) {
    throw new Error(`Delete failed: ${response.status}`);
  }
}

export async function retryDocument(docId: string): Promise<DocUploadResponse> {
  const response = await fetch(`${API_BASE_URL}/documents/${docId}/retry`, {
    method: 'POST',
    headers: authHeaders(),
  });
  if (!response.ok) {
    throw new Error(`Retry failed: ${response.status}`);
  }
  return response.json() as Promise<DocUploadResponse>;
}

export async function searchRegulations(query: string, topK: number = 8): Promise<RegulationSearchResponse> {
  const response = await fetch(`${API_BASE_URL}/knowledge/retrieval`, {
    method: 'POST',
    headers: authHeaders({
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }),
    body: JSON.stringify({ query, top_k: topK }),
  });

  if (!response.ok) {
    throw new Error(`Search failed: ${response.status}`);
  }

  const data = (await response.json()) as BackendKnowledgeResponse;
  return {
    query: data.query,
    total: data.total,
    results: data.results.map((item) => {
      const metadata = item.metadata || {};
      return {
        id: item.id,
        file: String(metadata.doc_name || metadata.filename || metadata.source || '法规知识库'),
        clause: String(metadata.section_title || metadata.clause_number || metadata.clause || '法规片段'),
        score: item.score,
        content: item.content,
        tags: [
          metadata.regulation_type ? String(metadata.regulation_type) : '',
          metadata.version ? `v${String(metadata.version)}` : '',
          metadata.page_number ? `p.${String(metadata.page_number)}` : '',
        ].filter(Boolean),
      };
    }),
  };
}

export function getDocumentDownloadUrl(docId: string): string {
  return `${API_BASE_URL}/documents/download/${docId}`;
}

export type { DocInfo, DocListResponse, DocUploadResponse };
