// SPDX-License-Identifier: LicenseRef-Commercial
import { invoke } from '@tauri-apps/api/core';

// --- Analytics ---

export interface AnalyticsSummary {
  totalSessions: number;
  totalCostUsd: number;
  totalTokens: number;
  totalTurns: number;
  totalToolCalls: number;
  avgCostPerSession: number;
  avgTokensPerSession: number;
  periodDays: number;
}

export interface DailyStats {
  date: string;
  sessionCount: number;
  costUsd: number;
  tokens: number;
  turns: number;
  toolCalls: number;
}

export interface ModelBreakdown {
  model: string;
  sessionCount: number;
  totalCostUsd: number;
  totalTokens: number;
  avgCostPerSession: number;
}

export const proAnalyticsSummary = (projectId: string, days?: number) =>
  invoke<AnalyticsSummary>('plugin:agor-pro|pro_analytics_summary', { projectId, days });

export const proAnalyticsDaily = (projectId: string, days?: number) =>
  invoke<DailyStats[]>('plugin:agor-pro|pro_analytics_daily', { projectId, days });

export const proAnalyticsModelBreakdown = (projectId: string, days?: number) =>
  invoke<ModelBreakdown[]>('plugin:agor-pro|pro_analytics_model_breakdown', { projectId, days });

// --- Export ---

export interface SessionReport {
  projectId: string;
  sessionId: string;
  markdown: string;
  costUsd: number;
  turnCount: number;
  toolCallCount: number;
  durationMinutes: number;
  model: string;
}

export interface ProjectSummaryReport {
  projectId: string;
  markdown: string;
  totalSessions: number;
  totalCostUsd: number;
  periodDays: number;
}

export const proExportSession = (projectId: string, sessionId: string) =>
  invoke<SessionReport>('plugin:agor-pro|pro_export_session', { projectId, sessionId });

export const proExportProjectSummary = (projectId: string, days?: number) =>
  invoke<ProjectSummaryReport>('plugin:agor-pro|pro_export_project_summary', { projectId, days });

// --- Profiles ---

export interface AccountProfile {
  id: string;
  displayName: string;
  email: string | null;
  provider: string;
  configDir: string;
  isActive: boolean;
}

export interface ActiveAccount {
  profileId: string;
  provider: string;
  configDir: string;
}

export const proListAccounts = () =>
  invoke<AccountProfile[]>('plugin:agor-pro|pro_list_accounts');

export const proGetActiveAccount = () =>
  invoke<ActiveAccount>('plugin:agor-pro|pro_get_active_account');

export const proSetActiveAccount = (profileId: string) =>
  invoke<ActiveAccount>('plugin:agor-pro|pro_set_active_account', { profileId });

// --- Marketplace ---

export interface CatalogPlugin {
  id: string;
  name: string;
  version: string;
  author: string;
  description: string;
  license: string | null;
  homepage: string | null;
  repository: string | null;
  downloadUrl: string;
  checksumSha256: string;
  sizeBytes: number | null;
  permissions: string[];
  tags: string[] | null;
  minAgorVersion: string | null;
  downloads: number | null;
  rating: number | null;
  createdAt: string | null;
  updatedAt: string | null;
}

export interface InstalledPlugin {
  id: string;
  name: string;
  version: string;
  author: string;
  description: string;
  permissions: string[];
  installPath: string;
  hasUpdate: boolean;
  latestVersion: string | null;
}

export const proMarketplaceFetchCatalog = () =>
  invoke<CatalogPlugin[]>('plugin:agor-pro|pro_marketplace_fetch_catalog');

export const proMarketplaceInstalled = () =>
  invoke<InstalledPlugin[]>('plugin:agor-pro|pro_marketplace_installed');

export const proMarketplaceInstall = (pluginId: string) =>
  invoke<InstalledPlugin>('plugin:agor-pro|pro_marketplace_install', { pluginId });

export const proMarketplaceUninstall = (pluginId: string) =>
  invoke<void>('plugin:agor-pro|pro_marketplace_uninstall', { pluginId });

export const proMarketplaceCheckUpdates = () =>
  invoke<InstalledPlugin[]>('plugin:agor-pro|pro_marketplace_check_updates');

export const proMarketplaceUpdate = (pluginId: string) =>
  invoke<InstalledPlugin>('plugin:agor-pro|pro_marketplace_update', { pluginId });

// --- Status ---

export const proStatus = () =>
  invoke<string>('plugin:agor-pro|pro_status');

// --- Budget Governor ---

export interface BudgetStatus { limit: number; used: number; remaining: number; percent: number; resetDate: string; }
export interface BudgetDecision { allowed: boolean; reason: string; remaining: number; }
export const proBudgetSet = (projectId: string, monthlyLimitTokens: number) => invoke<void>('plugin:agor-pro|pro_budget_set', { projectId, monthlyLimitTokens });
export const proBudgetGet = (projectId: string) => invoke<BudgetStatus>('plugin:agor-pro|pro_budget_get', { projectId });
export const proBudgetCheck = (projectId: string, estimatedTokens: number) => invoke<BudgetDecision>('plugin:agor-pro|pro_budget_check', { projectId, estimatedTokens });
export const proBudgetLogUsage = (projectId: string, sessionId: string, tokensUsed: number) => invoke<void>('plugin:agor-pro|pro_budget_log_usage', { projectId, sessionId, tokensUsed });
export const proBudgetList = () => invoke<Array<BudgetStatus & { projectId: string }>>('plugin:agor-pro|pro_budget_list');

// --- Smart Model Router ---

export interface ModelRecommendation { model: string; reason: string; estimatedCostFactor: number; }
export const proRouterRecommend = (projectId: string, role: string, promptLength: number, provider: string) => invoke<ModelRecommendation>('plugin:agor-pro|pro_router_recommend', { projectId, role, promptLength, provider });
export const proRouterSetProfile = (projectId: string, profile: string) => invoke<void>('plugin:agor-pro|pro_router_set_profile', { projectId, profile });
export const proRouterGetProfile = (projectId: string) => invoke<string>('plugin:agor-pro|pro_router_get_profile', { projectId });

// --- Persistent Memory ---

export interface MemoryFragment { id: number; projectId: string; content: string; source: string; trust: 'human' | 'agent' | 'auto'; confidence: number; createdAt: number; ttlDays: number; tags: string; }
export const proMemoryAdd = (projectId: string, content: string, source: string, tags: string) => invoke<number>('plugin:agor-pro|pro_memory_add', { projectId, content, source, tags });
export const proMemoryList = (projectId: string, limit: number) => invoke<MemoryFragment[]>('plugin:agor-pro|pro_memory_list', { projectId, limit });
export const proMemorySearch = (projectId: string, query: string) => invoke<MemoryFragment[]>('plugin:agor-pro|pro_memory_search', { projectId, query });
export const proMemoryDelete = (id: number) => invoke<void>('plugin:agor-pro|pro_memory_delete', { id });
export const proMemoryInject = (projectId: string, maxTokens: number) => invoke<string>('plugin:agor-pro|pro_memory_inject', { projectId, maxTokens });

// --- Git Context ---

export interface GitContext { branch: string; lastCommits: Array<{hash: string; message: string; author: string; timestamp: number}>; modifiedFiles: string[]; hasUnstaged: boolean; }
export interface PolicyDecision { allowed: boolean; branch: string; matchedPolicy: string | null; reason: string; }
export const proGitContext = (projectPath: string) => invoke<GitContext>('plugin:agor-pro|pro_git_context', { projectPath });
export const proGitInject = (projectPath: string, maxTokens: number) => invoke<string>('plugin:agor-pro|pro_git_inject', { projectPath, maxTokens });
export const proBranchCheck = (projectPath: string) => invoke<PolicyDecision>('plugin:agor-pro|pro_branch_check', { projectPath });

// --- Symbols ---

export interface CodeSymbol { name: string; kind: string; filePath: string; lineNumber: number; }
export const proSymbolsScan = (projectPath: string) => invoke<{filesScanned: number; symbolsFound: number; durationMs: number}>('plugin:agor-pro|pro_symbols_scan', { projectPath });
export const proSymbolsSearch = (projectPath: string, query: string) => invoke<CodeSymbol[]>('plugin:agor-pro|pro_symbols_search', { projectPath, query });
