import { api } from './client';
import type {
	Tenant, SystemStats, MemoryInfo, DiskInfo, UsageData,
	Credential, Task, RegisteredGroup
} from '$lib/types';

// System
export const getStats = () => api.get<SystemStats>('/stats');
export const loginWithCookie = (token: string) => api.post<{ message: string }>('/auth/login', { token });
export const logoutCookie = () => api.post<{ message: string }>('/auth/logout', {});
export const getSession = () => api.get<{ status: string }>('/auth/session');
export const getSettings = () => api.get<{ default_provider: string; default_model: string; default_pi_backend: string }>('/settings');
export const getPiModels = () => api.get<{ providers: { id: string; label: string; modelCount: number }[]; models: Record<string, { id: string; name: string }[]> }>('/pi-models');
export const updateSettings = (data: { default_provider?: string; default_model?: string; default_pi_backend?: string; concierge_bot_user_id?: string; concierge_tenant_id?: string }) =>
	api.post<{ message: string }>('/settings', data);
export const getMemory = () => api.get<MemoryInfo>('/memory');
export const getDisk = () => api.get<DiskInfo>('/disk');
export const getUsage = (days = 7, tenant?: string) =>
	api.get<UsageData>('/usage', { days: String(days), ...(tenant ? { tenant } : {}) });
export const getClaudeUsage = () => api.get<{ tokens: any[] }>('/claude-usage');

// Tenants
export const getTenants = () => api.get<Tenant[]>('/tenants');
export const createTenant = (data: Partial<Tenant> & { provision_discord?: boolean }) =>
	api.post<{ message: string; inviteUrl?: string; pairingCode?: string }>('/tenants', data);
export const updateTenant = (id: string, data: Partial<Tenant> & { daily_duration_mins?: number; daily_requests?: number }) =>
	api.put<{ message: string }>(`/tenants/${id}`, data);
export const deleteTenant = (id: string) =>
	api.del<{ message: string }>(`/tenants/${id}`);

// Groups
export const getTenantGroups = (tenantId: string) =>
	api.get<RegisteredGroup[]>(`/tenants/${tenantId}/groups`);
export const createTenantGroup = (tenantId: string, data: { jid: string; name?: string; folder: string; requiresTrigger?: boolean; isMain?: boolean }) =>
	api.post<{ message: string }>(`/tenants/${tenantId}/groups`, data);
export const updateTenantGroup = (tenantId: string, jid: string, data: { requires_trigger?: boolean; hooks_enabled?: boolean; hooks_rotate?: boolean }) =>
	api.patch<{ message: string }>(`/tenants/${tenantId}/groups/${encodeURIComponent(jid)}`, data);
export const deleteTenantGroup = (tenantId: string, jid: string) =>
	api.del<{ message: string }>(`/tenants/${tenantId}/groups/${encodeURIComponent(jid)}`);

// Channels
export const createTenantChannel = (tenantId: string, data: { name: string; requiresTrigger?: boolean }) =>
	api.post<{ message: string; channelId: string; jid: string }>(`/tenants/${tenantId}/channels`, data);

// WhatsApp
export const getWhatsAppStatus = () => api.get<{ connected: boolean; phone: string | null }>('/whatsapp/status');
export const startWhatsAppAuth = (phone: string) => api.post<{ code: string | null; message: string }>('/whatsapp/auth', { phone });
export const getWhatsAppAuthStatus = () => api.get<{ status: string; phone?: string; code?: string }>('/whatsapp/auth/status');
export const logoutWhatsApp = () => api.post<{ message: string }>('/whatsapp/logout');
export const registerWhatsAppChat = (tenantId: string, data: { type: string; jid?: string; name?: string; requiresTrigger?: boolean }) =>
	api.post<{ message: string; jid: string; folder: string }>(`/tenants/${tenantId}/whatsapp-chat`, data);

// Services/Compose
export const getTenantServices = (tenantId: string) =>
	api.get<any>(`/tenants/${tenantId}/services`);
export const getTenantSubdomains = (tenantId: string) =>
	api.get<string[]>(`/tenants/${tenantId}/subdomains`);
export const getTenantCaddyfile = (tenantId: string) =>
	api.get<{ content: string }>(`/tenants/${tenantId}/caddyfile`);
export const updateTenantCaddyfile = (tenantId: string, content: string) =>
	api.put<{ message: string }>(`/tenants/${tenantId}/caddyfile`, { content });
export const composeUp = (tenantId: string) =>
	api.post<{ message: string }>(`/tenants/${tenantId}/compose/up`);
export const composeDown = (tenantId: string) =>
	api.post<{ message: string }>(`/tenants/${tenantId}/compose/down`);
export const getComposeLogs = (tenantId: string) =>
	api.get<{ logs: string }>(`/tenants/${tenantId}/compose/logs`);

// Caddy
export const getCaddyConfig = () => api.get<{ systemConfig: string; tenantFiles: any[] }>('/caddy');

// NanoClaw Service
export const restartService = () => api.post<{ message: string }>('/service/restart');
export const stopService = () => api.post<{ message: string }>('/service/stop');
export const startService = () => api.post<{ message: string }>('/service/start');
export const getServiceLogs = () => api.get<{ logs: string }>('/service/logs');

// Credentials
export const getCredentials = () => api.get<Credential[]>('/credentials');
export const getCredential = (id: string) => api.get<Credential>(`/credentials/${id}`);
export const createCredential = (data: { id: string; provider: string; pi_backend?: string; type: string; label?: string; api_key?: string }) =>
	api.post<{ authorize_url?: string; message?: string }>('/credentials', data);
export const updateCredential = (id: string, data: Partial<Credential>) =>
	api.patch<{ message: string }>(`/credentials/${id}`, data);
export const deleteCredential = (id: string) =>
	api.del<{ message: string }>(`/credentials/${id}`);
export const callbackCredential = (id: string, data: { code: string; state: string }) =>
	api.post<{ message: string }>(`/credentials/${id}/callback`, data);
export const reloginCredential = (id: string) =>
	api.post<{ authorize_url: string; message: string; state: string }>(`/credentials/${id}/relogin`, {});
export const importCredentialAuth = (id: string, auth_json: string) =>
	api.post<{ message: string }>(`/credentials/${id}/import-auth`, { auth_json });
export const importPiHostAuth = (id: string) =>
	api.post<{ message: string }>(`/credentials/${id}/import-pi-host-auth`, {});
export const startCodexDeviceAuth = (id: string) =>
	api.post<{ id: string; authorize_url: string; user_code: string; message?: string }>(`/credentials/${id}/codex-device/start`, {});
export const finishCodexDeviceAuth = (id: string) =>
	api.post<{ id: string; status: 'ok' | 'pending'; message?: string; authorize_url?: string; user_code?: string }>(`/credentials/${id}/codex-device/finish`, {});
export const pollCodexDeviceStatus = (id: string) =>
	api.get<{ status: 'none' | 'pending' | 'ok'; id?: string; message?: string; authorize_url?: string; user_code?: string }>(`/credentials/${id}/codex-device/status`);
export const startPiLogin = (id: string) =>
	api.post<{ authorize_url: string; status: string }>(`/credentials/${id}/pi-login/start`, {});
export const pollPiLoginStatus = (id: string) =>
	api.get<{ status: 'idle' | 'awaiting_user' | 'complete' | 'error'; url?: string; instructions?: string; progress?: string[]; error?: string; needsManualCode?: boolean }>(`/credentials/${id}/pi-login/poll`);
export const submitPiLoginCode = (id: string, code: string) =>
	api.post<{ message: string }>(`/credentials/${id}/pi-login/code`, { code });
export const getCredentialUsageLatest = () =>
	api.get<{ snapshots: any[] }>(`/credentials/usage-latest`);
export const snapshotCredentialUsage = () =>
	api.post<{ message: string; captured_at: string; count: number }>(`/credentials/usage-snapshot`);

// Agents
export const getAgentContainers = (tenantId?: string) =>
	api.get<{ id: string; name: string; image: string; status: string; tenant: string; agent_status: string }[]>(
		'/agents/containers',
		tenantId ? { tenant: tenantId } : {},
	);

// Tasks
export const getTasks = () => api.get<Task[]>('/tasks');
export const createTask = (data: Partial<Task>) => api.post<Task>('/tasks', data);
export const updateTask = (id: string, data: Partial<Task>) => api.put<Task>(`/tasks/${id}`, data);
export const deleteTask = (id: string) => api.del<{ message: string }>(`/tasks/${id}`);
export const addTaskComment = (id: string, data: { author?: string; content: string }) =>
	api.post<Task>(`/tasks/${id}/comments`, data);

// Custom Domains
export const getCustomDomains = (tenantId?: string) =>
	api.get<import('$lib/types').CustomDomain[]>('/custom-domains', tenantId ? { tenant_id: tenantId } : {});
export const createCustomDomain = (data: { tenant_id: string; domain: string; target: string }) =>
	api.post<import('$lib/types').CustomDomain>('/custom-domains', data);
export const activateCustomDomain = (id: string) =>
	api.post<import('$lib/types').CustomDomain>(`/custom-domains/${id}/activate`, {});
export const deleteCustomDomain = (id: string) =>
	api.del<{ message: string }>(`/custom-domains/${id}`);


// Skills
export type SkillEntry = { dir: string; name: string; description: string; allowedTools: string; source: string; body: string };
export const getSkills = () => api.get<SkillEntry[]>("/skills");
export const getSkill = (skillId: string, source?: string) =>
	api.get<SkillEntry>("/skills/" + skillId, source ? { source } : {});

// Caddy ping
export const pingUrl = (url: string) => api.get<{ url: string; status: number; ok: boolean; error?: string }>('/caddy/ping', { url });

