import type {
  IReactiveFileSystem,
  FileSystemEventPayloads,
} from "@firesystem/core";

/**
 * Project configuration for loading
 */
export interface ProjectConfig {
  id: string;
  name: string;
  source: ProjectSource;
  metadata?: Record<string, any>;
}

/**
 * Source configuration for different storage types
 */
export interface ProjectSource {
  type: "memory" | "indexeddb" | "s3" | "json-url" | "api" | "github" | "git";
  config: any;
  auth?: SourceAuth;
}

/**
 * Authentication configuration for sources
 */
export interface SourceAuth {
  type: "bearer" | "basic" | "token" | "oauth2";
  credentials: any;
  refresh?: () => Promise<SourceAuth>;
}

/**
 * Project metadata
 */
export interface ProjectMetadata {
  created: Date;
  modified: Date;
  lastOpened: Date;
  size?: number;
  fileCount?: number;
  [key: string]: any;
}

/**
 * Project state
 */
export type ProjectState = "loading" | "loaded" | "error" | "unloading" | "disabled";

/**
 * Active project with file system
 */
export interface Project {
  id: string;
  name: string;
  source: ProjectSource;
  fs: IReactiveFileSystem;
  metadata: ProjectMetadata;
  state: ProjectState;
  error?: Error;
  lastAccessed: Date;
  memoryUsage?: number;
  accessCount: number;
}

/**
 * Workspace configuration
 */
export interface WorkspaceConfig {
  version: string;
  projects: ProjectConfig[];
  activeProjectId?: string;
  settings?: WorkspaceSettings;
}

/**
 * Workspace settings
 */
export interface WorkspaceSettings {
  maxActiveProjects?: number;      // Auto-disable when exceeded
  autoDisableAfter?: number;       // Ms of inactivity before auto-disable
  keepFocusedActive?: boolean;     // Never auto-disable focused project
  autoSave?: boolean;
  autoSaveInterval?: number;
  memoryThreshold?: number;        // Bytes before triggering optimization
  [key: string]: any;
}

/**
 * Source loader interface
 */
export interface SourceLoader {
  type: string;

  /**
   * Create the appropriate file system for this source
   */
  createFileSystem(source: ProjectSource): Promise<IReactiveFileSystem>;

  /**
   * Initialize the file system with data from source
   */
  initialize(fs: IReactiveFileSystem, source: ProjectSource): Promise<void>;

  /**
   * Optional: Save file system back to source
   */
  save?(fs: IReactiveFileSystem, source: ProjectSource): Promise<void>;
}

/**
 * Workspace events
 */
export interface WorkspaceEventPayloads extends FileSystemEventPayloads {
  // Project lifecycle events
  "project:loading": { projectId: string };
  "project:loaded": { project: Project };
  "project:activated": { projectId: string; previousId?: string };
  "project:deactivated": { projectId: string };
  "project:unloading": { projectId: string };
  "project:unloaded": { projectId: string };
  "project:error": { projectId: string; error: Error };

  // Project file system events (forwarded)
  "project:file:reading": { projectId: string; path: string };
  "project:file:read": { projectId: string; path: string; size: number };
  "project:file:writing": { projectId: string; path: string; size?: number };
  "project:file:written": { projectId: string; path: string; size: number };
  "project:file:deleting": { projectId: string; path: string };
  "project:file:deleted": { projectId: string; path: string };
  "project:dir:creating": {
    projectId: string;
    path: string;
    recursive: boolean;
  };
  "project:dir:created": { projectId: string; path: string };
  "project:dir:deleting": {
    projectId: string;
    path: string;
    recursive: boolean;
  };
  "project:dir:deleted": { projectId: string; path: string };

  // Project operations
  "project:converting": { projectId: string; targetSource: ProjectSource };
  "project:converted": { projectId: string; source: ProjectSource };
  "project:syncing": { projectId: string; targetSource: ProjectSource };
  "project:synced": { projectId: string; source: ProjectSource };

  // Workspace events
  "workspace:initializing": void;
  "workspace:initialized": { projectCount: number };
  "workspace:clearing": void;
  "workspace:cleared": void;
  "workspace:error": { error: Error };

  // Import/Export events
  "workspace:importing": { source: string };
  "workspace:imported": { source: string };
  "workspace:import-failed": { source: string; error: any };

  // Project management events
  "project:removed": { projectId: string };
  "project:delete-confirm": { projectId: string; project: any; cancelled?: boolean };
  "project:deleted": { projectId: string; deletedData: boolean };
  "project:disabling": { projectId: string };
  "project:disabled": { projectId: string; hasLocalData: boolean; reason: string };
  "project:enabled": { projectId: string };
  "project:files-copied": { sourceId: string; targetId: string; fileCount: number };
}

/**
 * Memory source configuration
 */
export interface MemorySourceConfig {
  initialData?: {
    files: Array<{
      path: string;
      type: "file" | "directory";
      content?: any;
      metadata?: Record<string, any>;
    }>;
  };
  initialDataUrl?: string;
}

/**
 * IndexedDB source configuration
 */
export interface IndexedDBSourceConfig {
  dbName: string;
  version?: number;
}

/**
 * JSON URL source configuration
 */
export interface JsonUrlSourceConfig {
  url: string;
  headers?: Record<string, string>;
}

/**
 * API source configuration
 */
export interface ApiSourceConfig {
  baseUrl: string;
  projectId: string;
  headers?: Record<string, string>;
  endpoints?: {
    files?: string;
    file?: string;
    upload?: string;
  };
}

/**
 * GitHub source configuration
 */
export interface GitHubSourceConfig {
  owner: string;
  repo: string;
  branch?: string;
  path?: string;
  readOnly?: boolean;
}

/**
 * Source configurations map
 */
export interface SourceConfigMap {
  memory: MemorySourceConfig;
  indexeddb: IndexedDBSourceConfig;
  "json-url": JsonUrlSourceConfig;
  api: ApiSourceConfig;
  github: GitHubSourceConfig;
}

/**
 * Project statistics
 */
export interface ProjectStats {
  fileCount: number;
  directoryCount: number;
  totalSize: number;
  lastModified: Date;
}

/**
 * Workspace statistics
 */
export interface WorkspaceStats {
  total: number;                   // Total configured projects
  active: number;                  // Currently loaded projects
  disabled: number;                // Disabled but configured
  focused: string | null;          // Currently focused project ID
  memoryUsage: string;            // Human-readable memory usage
  connections: Record<string, number>;  // Active connections by type
}

/**
 * Project metrics
 */
export interface ProjectMetrics {
  fileCount: number;
  totalSize: number;
  lastModified: Date;
  accessCount: number;
  averageFileSize: number;
  largestFile: { path: string; size: number };
}

/**
 * Sync options for cross-project operations
 */
export interface SyncOptions {
  overwrite?: boolean;
  filter?: (path: string) => boolean;
  progress?: (copied: number, total: number) => void;
}

/**
 * Project diff result
 */
export interface ProjectDiff {
  added: string[];
  modified: string[];
  deleted: string[];
  unchanged: string[];
}

/**
 * Memory optimization report
 */
export interface OptimizationReport {
  projectsDisabled: string[];
  memoryFreed: number;
  connectionsReleased: number;
}
