import { apiRequest } from './api';

export type SchoolRecommendationRisk = 'safe' | 'balanced' | 'sprint' | 'unknown';

export interface GenerateSchoolRecommendationInput {
  regionId?: string;
  estimatedScore?: number;
  examTrack?: string;
  preferredCity?: string;
  targetSchoolId?: string;
  targetMajorId?: string;
  riskPreference?: 'safe' | 'balanced' | 'sprint';
  constraints?: string;
  notes?: string;
  recommendationLimit?: number;
}

export interface SchoolRecommendationCandidate {
  schoolId?: string | null;
  schoolName: string;
  majorId?: string | null;
  majorName?: string | null;
  latestYear?: number | null;
  latestScore?: number | null;
  averageScore?: number | null;
  scoreGap?: number | null;
  riskLevel: SchoolRecommendationRisk;
  confidence: number;
  reason: string;
  scorelineTrend?: {
    years: number[];
    scores: Array<number | null>;
    direction: 'up' | 'down' | 'flat' | 'unknown';
  };
  tags?: string[];
}

export interface SchoolRecommendationReportResult {
  schemaVersion: 'school-recommendation-report-v1';
  summary: string;
  riskLevel: SchoolRecommendationRisk;
  recommendedSchools: SchoolRecommendationCandidate[];
  actionPlan: string[];
  disclaimers: string[];
  dataCoverage: Record<string, unknown>;
}

export interface SchoolRecommendationReport {
  id: string;
  tenantId: string;
  userId: string;
  regionId?: string | null;
  status: 'draft' | 'generated' | 'failed';
  provider: string;
  model?: string | null;
  promptVersion: string;
  inputPayload: GenerateSchoolRecommendationInput;
  contextPayload: Record<string, unknown>;
  resultPayload: SchoolRecommendationReportResult;
  errorMessage?: string | null;
  generatedAt?: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface SchoolRecommendationExport {
  reportId: string;
  format: 'markdown' | 'html';
  fileName: string;
  mimeType: string;
  contentBase64: string;
  contentText?: string;
  sha256: string;
  sizeBytes: number;
}

export async function generateSchoolRecommendation(input: GenerateSchoolRecommendationInput) {
  return apiRequest<{ item?: SchoolRecommendationReport }>('/api/ai/school-recommendations/generate', {
    method: 'POST',
    body: input,
  });
}

export async function loadSchoolRecommendationReports(query: { regionId?: string; limit?: number } = {}) {
  return apiRequest<{ items?: SchoolRecommendationReport[] }>('/api/ai/school-recommendations', {
    query,
  });
}

export async function loadSchoolRecommendationReport(reportId: string) {
  return apiRequest<{ item?: SchoolRecommendationReport }>('/api/ai/school-recommendations/detail', {
    query: { reportId },
  });
}

export async function exportSchoolRecommendationReport(reportId: string, format: 'markdown' | 'html' = 'markdown') {
  return apiRequest<{ item?: SchoolRecommendationExport }>('/api/ai/school-recommendations/export', {
    query: { reportId, format },
  });
}
