/**
 * tRPC Context
 *
 * Defines the context available to all tRPC procedures.
 * Context is injected into each procedure call.
 */

import type { EventBus, DomainEvent } from '../events/types.js';
import type { AgentManager } from '../agent/types.js';
import type { TaskRepository } from '../db/repositories/task-repository.js';
import type { MessageRepository } from '../db/repositories/message-repository.js';
import type { InitiativeRepository } from '../db/repositories/initiative-repository.js';
import type { PhaseRepository } from '../db/repositories/phase-repository.js';
import type { PageRepository } from '../db/repositories/page-repository.js';
import type { ProjectRepository } from '../db/repositories/project-repository.js';
import type { AccountRepository } from '../db/repositories/account-repository.js';
import type { ChangeSetRepository } from '../db/repositories/change-set-repository.js';
import type { LogChunkRepository } from '../db/repositories/log-chunk-repository.js';
import type { ConversationRepository } from '../db/repositories/conversation-repository.js';
import type { ChatSessionRepository } from '../db/repositories/chat-session-repository.js';
import type { ReviewCommentRepository } from '../db/repositories/review-comment-repository.js';
import type { ErrandRepository } from '../db/repositories/errand-repository.js';
import type { AccountCredentialManager } from '../agent/credentials/types.js';
import type { DispatchManager, PhaseDispatchManager } from '../dispatch/types.js';
import type { CoordinationManager } from '../coordination/types.js';
import type { BranchManager } from '../git/branch-manager.js';
import type { ExecutionOrchestrator } from '../execution/orchestrator.js';
import type { PreviewManager } from '../preview/index.js';
import type { ProjectSyncManager } from '../git/remote-sync.js';

// Re-export for convenience
export type { EventBus, DomainEvent };

/**
 * Context available to all tRPC procedures.
 */
export interface TRPCContext {
  /** Event bus for inter-module communication */
  eventBus: EventBus;
  /** When the server started (null if not yet started) */
  serverStartedAt: Date | null;
  /** Number of managed processes */
  processCount: number;
  /** Agent manager for agent lifecycle operations (optional until server wiring complete) */
  agentManager?: AgentManager;
  /** Task repository for task CRUD operations (optional until server wiring complete) */
  taskRepository?: TaskRepository;
  /** Message repository for agent-user communication (optional until server wiring complete) */
  messageRepository?: MessageRepository;
  /** Dispatch manager for task queue operations (optional until server wiring complete) */
  dispatchManager?: DispatchManager;
  /** Coordination manager for merge queue operations (optional until server wiring complete) */
  coordinationManager?: CoordinationManager;
  /** Initiative repository for initiative CRUD operations (optional until server wiring complete) */
  initiativeRepository?: InitiativeRepository;
  /** Phase repository for phase CRUD operations (optional until server wiring complete) */
  phaseRepository?: PhaseRepository;
  /** Phase dispatch manager for phase queue operations (optional until server wiring complete) */
  phaseDispatchManager?: PhaseDispatchManager;
  /** Page repository for page CRUD operations (optional until server wiring complete) */
  pageRepository?: PageRepository;
  /** Project repository for project CRUD and initiative-project junction operations */
  projectRepository?: ProjectRepository;
  /** Account repository for account CRUD and load balancing */
  accountRepository?: AccountRepository;
  /** Change set repository for agent change set operations */
  changeSetRepository?: ChangeSetRepository;
  /** Log chunk repository for agent output persistence */
  logChunkRepository?: LogChunkRepository;
  /** Credential manager for account OAuth token management */
  credentialManager?: AccountCredentialManager;
  /** Branch manager for git branch operations */
  branchManager?: BranchManager;
  /** Execution orchestrator for phase merge/review workflow */
  executionOrchestrator?: ExecutionOrchestrator;
  /** Preview manager for Docker-based preview deployments */
  previewManager?: PreviewManager;
  /** Conversation repository for inter-agent communication */
  conversationRepository?: ConversationRepository;
  /** Chat session repository for iterative phase/task chat */
  chatSessionRepository?: ChatSessionRepository;
  /** Review comment repository for inline review comments on phase diffs */
  reviewCommentRepository?: ReviewCommentRepository;
  /** Errand repository for errand CRUD operations */
  errandRepository?: ErrandRepository;
  /** Project sync manager for remote fetch/sync operations */
  projectSyncManager?: ProjectSyncManager;
  /** Absolute path to the workspace root (.cwrc directory) */
  workspaceRoot?: string;
}

/**
 * Options for creating the tRPC context.
 */
export interface CreateContextOptions {
  eventBus: EventBus;
  serverStartedAt: Date | null;
  processCount: number;
  agentManager?: AgentManager;
  taskRepository?: TaskRepository;
  messageRepository?: MessageRepository;
  dispatchManager?: DispatchManager;
  coordinationManager?: CoordinationManager;
  initiativeRepository?: InitiativeRepository;
  phaseRepository?: PhaseRepository;
  phaseDispatchManager?: PhaseDispatchManager;
  pageRepository?: PageRepository;
  projectRepository?: ProjectRepository;
  accountRepository?: AccountRepository;
  changeSetRepository?: ChangeSetRepository;
  logChunkRepository?: LogChunkRepository;
  credentialManager?: AccountCredentialManager;
  branchManager?: BranchManager;
  executionOrchestrator?: ExecutionOrchestrator;
  previewManager?: PreviewManager;
  conversationRepository?: ConversationRepository;
  chatSessionRepository?: ChatSessionRepository;
  reviewCommentRepository?: ReviewCommentRepository;
  errandRepository?: ErrandRepository;
  projectSyncManager?: ProjectSyncManager;
  workspaceRoot?: string;
}

/**
 * Creates the tRPC context for procedure calls.
 *
 * @param options - Context creation options
 * @returns The tRPC context
 */
export function createContext(options: CreateContextOptions): TRPCContext {
  return {
    eventBus: options.eventBus,
    serverStartedAt: options.serverStartedAt,
    processCount: options.processCount,
    agentManager: options.agentManager,
    taskRepository: options.taskRepository,
    messageRepository: options.messageRepository,
    dispatchManager: options.dispatchManager,
    coordinationManager: options.coordinationManager,
    initiativeRepository: options.initiativeRepository,
    phaseRepository: options.phaseRepository,
    phaseDispatchManager: options.phaseDispatchManager,
    pageRepository: options.pageRepository,
    projectRepository: options.projectRepository,
    accountRepository: options.accountRepository,
    changeSetRepository: options.changeSetRepository,
    logChunkRepository: options.logChunkRepository,
    credentialManager: options.credentialManager,
    branchManager: options.branchManager,
    executionOrchestrator: options.executionOrchestrator,
    previewManager: options.previewManager,
    conversationRepository: options.conversationRepository,
    chatSessionRepository: options.chatSessionRepository,
    reviewCommentRepository: options.reviewCommentRepository,
    errandRepository: options.errandRepository,
    projectSyncManager: options.projectSyncManager,
    workspaceRoot: options.workspaceRoot,
  };
}
