import { v4 as uuidv4, validate as uuidValidate } from 'uuid';

type AssistantSettingsConfig = {
  allowActionPanelAiRequests?: boolean;
  assistantEnabled?: boolean;
  allowLogReads?: boolean;
  allowWriteOperations?: boolean;
  autoApproveSafeWriteOperations?: boolean;
  requireReadApproval?: boolean;
  setupCompleted?: boolean;
};

type AssistantRestEndpointsConfig = {
  settings?: string;
  attachments?: string;
  capabilities?: string;
  commands?: string;
};

type AssistantConfig = {
  restNonce?: string;
  nonceRefreshUrl?: string;
  nonceRefreshNonce?: string;
  chatEndpoint?: string;
  cssUrl?: string;
  restEndpoints?: AssistantRestEndpointsConfig;
  settings?: AssistantSettingsConfig;
};

declare global {
  interface Window {
    actionPanelAiConfig?: AssistantConfig;
  }
}

const primaryConfig: AssistantConfig | undefined =
  typeof window !== 'undefined' ? (window as any).actionPanelAiConfig : undefined;
const parentConfig: AssistantConfig | undefined =
  typeof window !== 'undefined' && window.parent ? (window.parent as any).actionPanelAiConfig : undefined;
const RESOLVED_PLUGIN_CONFIG: AssistantConfig | undefined = primaryConfig ?? parentConfig;

const TARGET = import.meta.env.VITE_TARGET as 'web' | 'wordpress';
const DEPLOYMENT = import.meta.env.VITE_DEPLOYMENT as 'production' | 'staging';
const WEB_API_BASE_URL = import.meta.env.VITE_API_BASE_URL as string | undefined;

function resolveApiBaseUrl(): string {
  if (TARGET === 'wordpress') {
    const chatEndpoint = RESOLVED_PLUGIN_CONFIG?.chatEndpoint?.trim();
    if (!chatEndpoint) {
      throw new Error('Missing actionPanelAiConfig.chatEndpoint for WordPress runtime.');
    }

    return chatEndpoint.replace(/\/+$/, '');
  }

  const webApiBaseUrl = WEB_API_BASE_URL?.trim();
  if (!webApiBaseUrl) {
    throw new Error('Missing VITE_API_BASE_URL for web runtime.');
  }

  return webApiBaseUrl.replace(/\/+$/, '');
}

export const API_BASE_URL = resolveApiBaseUrl();
export const TARGET_ENV = TARGET;
export const IS_WORDPRESS = TARGET === 'wordpress';
export const DEPLOYMENT_ENV = DEPLOYMENT;
export const ASSISTANT_BRAND_NAME = IS_WORDPRESS ? 'ActionPanel AI' : 'WP Assistant';

export const PLUGIN_ASSISTANT_SETTINGS: AssistantSettingsConfig = RESOLVED_PLUGIN_CONFIG?.settings ?? {};
export const SETUP_COMPLETED = TARGET === 'wordpress'
  ? (PLUGIN_ASSISTANT_SETTINGS.setupCompleted ?? true)
  : true;
export const ALLOW_ACTIONPANEL_AI_REQUESTS = TARGET === 'wordpress'
  ? Boolean(PLUGIN_ASSISTANT_SETTINGS.allowActionPanelAiRequests ?? PLUGIN_ASSISTANT_SETTINGS.assistantEnabled)
  : true;

export function syncPluginAssistantSettings(settings: AssistantSettingsConfig) {
  Object.assign(PLUGIN_ASSISTANT_SETTINGS, settings);
  if (RESOLVED_PLUGIN_CONFIG) {
    RESOLVED_PLUGIN_CONFIG.settings = {
      ...(RESOLVED_PLUGIN_CONFIG.settings ?? {}),
      ...settings,
    };
  }
}

export function getAllowActionPanelAiRequests(): boolean {
  return TARGET === 'wordpress'
    ? Boolean(PLUGIN_ASSISTANT_SETTINGS.allowActionPanelAiRequests ?? PLUGIN_ASSISTANT_SETTINGS.assistantEnabled)
    : true;
}

let restNonce = RESOLVED_PLUGIN_CONFIG?.restNonce ?? '';

export function getRestNonce(): string {
  return restNonce;
}

export function setRestNonce(nonce: string) {
  restNonce = nonce;
  try {
    if (primaryConfig) primaryConfig.restNonce = nonce;
    if (parentConfig) parentConfig.restNonce = nonce;
  } catch {
    // Ignore cross-frame mutation issues.
  }
}

export const NONCE_REFRESH_URL = RESOLVED_PLUGIN_CONFIG?.nonceRefreshUrl ?? '';
export const NONCE_REFRESH_NONCE = RESOLVED_PLUGIN_CONFIG?.nonceRefreshNonce ?? '';

const DEFAULT_PLUGIN_REST_ENDPOINTS: Required<AssistantRestEndpointsConfig> = {
  settings: '/wp-json/actionpanel-ai/v1/settings',
  attachments: '/wp-json/actionpanel-ai/v1/attachments',
  capabilities: '/wp-json/actionpanel-ai/v1/capabilities',
  commands: '/wp-json/actionpanel-ai/v1/commands',
};

export const PLUGIN_REST_ENDPOINTS: Required<AssistantRestEndpointsConfig> = {
  settings: RESOLVED_PLUGIN_CONFIG?.restEndpoints?.settings ?? DEFAULT_PLUGIN_REST_ENDPOINTS.settings,
  attachments: RESOLVED_PLUGIN_CONFIG?.restEndpoints?.attachments ?? DEFAULT_PLUGIN_REST_ENDPOINTS.attachments,
  capabilities: RESOLVED_PLUGIN_CONFIG?.restEndpoints?.capabilities ?? DEFAULT_PLUGIN_REST_ENDPOINTS.capabilities,
  commands: RESOLVED_PLUGIN_CONFIG?.restEndpoints?.commands ?? DEFAULT_PLUGIN_REST_ENDPOINTS.commands,
};

// --- Plugin identity & auth token helpers ---
const PLUGIN_SESSION_KEY = IS_WORDPRESS ? 'actionpanel_ai_plugin_session_id' : 'wpa_plugin_session_id';
const AUTH_TOKEN_KEY = IS_WORDPRESS ? 'actionpanel_ai_auth_token' : 'wpa_auth_token';

export function getOrCreatePluginSessionId(): string {
  try {
    const existing = localStorage.getItem(PLUGIN_SESSION_KEY);
    if (existing && uuidValidate(existing)) {
      const normalized = existing.toLowerCase();
      if (normalized !== existing) localStorage.setItem(PLUGIN_SESSION_KEY, normalized);
      return normalized;
    }
    const id = uuidv4();
    localStorage.setItem(PLUGIN_SESSION_KEY, id);
    return id;
  } catch {
    // Fallback to ephemeral
    return uuidv4();
  }
}

export function getAuthToken(): string | null {
  try { return localStorage.getItem(AUTH_TOKEN_KEY); } catch { return null; }
}
export function setAuthToken(token: string) {
  try { localStorage.setItem(AUTH_TOKEN_KEY, token); } catch {}
}
export function clearAuthToken() {
  try { localStorage.removeItem(AUTH_TOKEN_KEY); } catch {}
}
