import request from './request'
import type {
  DocumentRecommendations,
  EntityDetailResponse,
  EntitySearchResult,
  GraphData,
  PaginatedGraphData,
  PolicyChainResponse,
  RelatedDocItem,
  RevisionHistoryResponse,
  SameThemeDocItem,
} from '@/types/graph'

const BASE = '/api/ai/v1/graph'

/**
 * Search entity nodes by name (partial match).
 */
export function searchEntities(
  name: string,
  label?: string,
  limit = 20,
): Promise<EntitySearchResult[]> {
  return request
    .post<EntitySearchResult[]>(`${BASE}/search`, { name, label, limit })
    .then((res) => res.data)
}

/**
 * Get entity node detail + neighbourhood subgraph.
 */
export function getEntityDetail(
  entityId: string,
  depth = 2,
  maxNodes = 300,
): Promise<EntityDetailResponse> {
  return request
    .get<EntityDetailResponse>(`${BASE}/entity/${entityId}`, {
      params: { depth, max_nodes: maxNodes },
    })
    .then((res) => res.data)
}

/**
 * Get documents connected to a given entity.
 * When entityKey is provided, uses key_property-based matching for precision.
 */
export function getRelatedDocs(
  entityName: string,
  entityLabel: string,
  limit = 20,
  entityKey?: string,
): Promise<RelatedDocItem[]> {
  return request
    .post<RelatedDocItem[]>(`${BASE}/related-docs`, {
      entity_name: entityName,
      entity_label: entityLabel,
      entity_key: entityKey || undefined,
      limit,
    })
    .then((res) => res.data)
}

/**
 * Get all entities for a document (grouped by label).
 */
export function getDocumentEntities(
  docId: string,
): Promise<Record<string, any[]>> {
  return request
    .get<{ doc_id: string; entities: Record<string, any[]> }>(
      `${BASE}/document/${docId}/entities`,
    )
    .then((res) => res.data.entities)
}

/**
 * Graph overview — most-connected docs or docs filtered by topic/entity.
 * 支持 cursor 分页，用于渐进式加载大图。
 */
export function getGraphOverview(
  entityName?: string,
  label?: string,
  limit = 500,
  cursor?: string,
): Promise<PaginatedGraphData> {
  return request
    .get<PaginatedGraphData>(`${BASE}/overview`, {
      params: { entity_name: entityName, label, limit, cursor },
    })
    .then((res) => res.data)
}

export function getDocumentRecommendations(
  docId: string,
  limit = 10,
): Promise<DocumentRecommendations> {
  return request
    .get<DocumentRecommendations>(`${BASE}/document/${docId}/recommendations`, {
      params: { limit },
    })
    .then((res) => res.data)
}

export function getPolicyChain(
  docId: string,
  maxDepth = 5,
): Promise<PolicyChainResponse> {
  return request
    .get<PolicyChainResponse>(`${BASE}/document/${docId}/policy-chain`, {
      params: { max_depth: maxDepth },
    })
    .then((res) => res.data)
}

export function getRevisionHistory(
  docId: string,
  maxDepth = 5,
): Promise<RevisionHistoryResponse> {
  return request
    .get<RevisionHistoryResponse>(`${BASE}/document/${docId}/revision-history`, {
      params: { max_depth: maxDepth },
    })
    .then((res) => res.data)
}

export function getSameThemeDocuments(
  docId: string,
  limit = 20,
): Promise<SameThemeDocItem[]> {
  return request
    .get<SameThemeDocItem[]>(`${BASE}/document/${docId}/same-theme`, {
      params: { limit },
    })
    .then((res) => res.data)
}

// ---------------------------------------------------------------------------
// Entity knowledge cards (Sprint 4)
// ---------------------------------------------------------------------------

export interface PolicyCard {
  name: string
  summary: string
  policy_id: string
  properties: Record<string, any>
  assigned_orgs: string[]
  implementing_tasks: { name: string; task_id: string }[]
  supported_projects: { name: string; project_id: string }[]
  related_themes: string[]
  source_docs: { doc_id: string; title: string; doc_code: string; publish_date: string }[]
}

export interface TaskCard {
  name: string
  task_id: string
  properties: Record<string, any>
  lead_orgs: string[]
  assist_orgs: string[]
  implementing_policies: { name: string; policy_id: string }[]
  evaluating_indicators: string[]
  budgets: { name: string; amount: string }[]
  source_docs: { doc_id: string; title: string; doc_code: string; publish_date: string }[]
}

export interface ProjectCard {
  name: string
  project_id: string
  properties: Record<string, any>
  implementing_orgs: string[]
  locations: string[]
  supporting_policies: { name: string; policy_id: string }[]
  budgets: { name: string; amount: string }[]
  technologies: string[]
  evaluating_indicators: string[]
  source_docs: { doc_id: string; title: string; doc_code: string; publish_date: string }[]
}

// ---------------------------------------------------------------------------
// V1.5 new entity card interfaces
// ---------------------------------------------------------------------------

export interface CardRelatedDoc {
  doc_id: string
  title: string
  doc_code: string
}

export interface SystemCard {
  name: string
  properties: Record<string, any>
  operated_by: string[]
  managed_data: string[]
  technologies: string[]
  related_docs: CardRelatedDoc[]
}

export interface DataResourceCard {
  name: string
  properties: Record<string, any>
  managed_by_systems: string[]
  conforms_to: string[]
  related_docs: CardRelatedDoc[]
}

export interface BudgetCard {
  name: string
  properties: Record<string, any>
  funded_tasks: { name: string; task_id: string }[]
  funded_projects: { name: string; project_id: string }[]
  related_docs: CardRelatedDoc[]
}

export interface IndicatorCard {
  name: string
  properties: Record<string, any>
  evaluated_tasks: { name: string; task_id: string }[]
  evaluated_projects: { name: string; project_id: string }[]
  related_docs: CardRelatedDoc[]
}

export interface IndustryCard {
  name: string
  properties: Record<string, any>
  supported_by_policies: { name: string; policy_id: string }[]
  located_in: string[]
  managed_by: string[]
  related_docs: CardRelatedDoc[]
}

export function getPolicyCard(entityKey: string): Promise<PolicyCard> {
  return request
    .get<PolicyCard>(`${BASE}/policy/${entityKey}`)
    .then((res) => res.data)
}

export function getTaskCard(entityKey: string): Promise<TaskCard> {
  return request
    .get<TaskCard>(`${BASE}/task/${entityKey}`)
    .then((res) => res.data)
}

export function getProjectCard(entityKey: string): Promise<ProjectCard> {
  return request
    .get<ProjectCard>(`${BASE}/project/${entityKey}`)
    .then((res) => res.data)
}

export function getSystemCard(entityKey: string): Promise<SystemCard> {
  return request
    .get<SystemCard>(`${BASE}/system/${entityKey}`)
    .then((res) => res.data)
}

export function getDataResourceCard(entityKey: string): Promise<DataResourceCard> {
  return request
    .get<DataResourceCard>(`${BASE}/data-resource/${entityKey}`)
    .then((res) => res.data)
}

export function getBudgetCard(entityKey: string): Promise<BudgetCard> {
  return request
    .get<BudgetCard>(`${BASE}/budget/${entityKey}`)
    .then((res) => res.data)
}

export function getIndicatorCard(entityKey: string): Promise<IndicatorCard> {
  return request
    .get<IndicatorCard>(`${BASE}/indicator/${entityKey}`)
    .then((res) => res.data)
}

export function getIndustryCard(entityKey: string): Promise<IndustryCard> {
  return request
    .get<IndustryCard>(`${BASE}/industry/${entityKey}`)
    .then((res) => res.data)
}
