import { AgentRunner, RunnerStatus } from "./AgentRunner";
import { SessionPersister } from "./SessionPersister";

export class MockRunner extends AgentRunner {
  id: string;
  name: string;
  type: 'mock' | 'claude' = 'mock';
  status: 'idle' | 'running' | 'stopped' = 'idle';
  createdAt: string;
  logs: string[] = [];
  
  private intervalId: NodeJS.Timeout | null = null;
  private mockSteps = [
    "[NeuralLoom] Loading virtual PTY context...",
    "[NeuralLoom] Spawning sandbox mock runtime environment...",
    "[Mock Agent] Model online (v2.0-mock-flash). Dedicated memory allocated.",
    "[Mock Agent] System rules parsed successfully from global context registry.",
    "[Mock Agent] Awaiting developer commands. Type '/help' to list mock skills."
  ];
  private stepIndex = 0;

  constructor(id: string, name?: string) {
    super();
    this.id = id;
    this.name = name || `Mock Session ${id.substring(0, 8)}`;
    this.createdAt = new Date().toISOString();
  }

  private appendLog(line: string) {
    this.logs.push(line);
    this.parseTokenUsage(line);
    this.emitOutput(line + "\r\n");
    SessionPersister.saveSession(this);
  }

  async start(): Promise<void> {
    if (this.status === 'running') return;
    this.status = 'running';
    
    // Add banner
    this.appendLog("\x1b[1;35m==================================================\x1b[0m");
    this.appendLog("\x1b[1;36m       NEURALLOOM SIMULATED AGENT ENVIRONMENT     \x1b[0m");
    this.appendLog("\x1b[1;35m==================================================\x1b[0m");
    
    // Post initial log immediately
    if (this.stepIndex < this.mockSteps.length) {
      this.appendLog(this.mockSteps[this.stepIndex++]);
    }

    // Schedule subsequent logs
    this.intervalId = setInterval(() => {
      this.tokenUsage.input += Math.floor(Math.random() * 50) + 10;
      this.tokenUsage.output += Math.floor(Math.random() * 20) + 5;
      this.tokenUsage.cost = (this.tokenUsage.input * 0.000003) + (this.tokenUsage.output * 0.000015);

      if (this.stepIndex < this.mockSteps.length) {
        this.appendLog(this.mockSteps[this.stepIndex++]);
      } else {
        // Just general ambient telemetry mock log
        const time = new Date().toLocaleTimeString();
        this.appendLog(`[${time}] [Telemetry] CPU utilization 1.2% | Memory 142MB | Link stable.`);
      }
    }, 4000);
  }

  async stop(): Promise<void> {
    this.status = 'stopped';
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
    this.appendLog("\x1b[1;31m[System] Process terminated. Connection closed.\x1b[0m");
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  async sendInput(text: string, _isRaw?: boolean): Promise<void> {
    if (this.status !== 'running') {
      this.appendLog(`\x1b[1;31m[Error] Cannot write input: process is ${this.status}.\x1b[0m`);
      return;
    }
    
    // Echo the command back as user prompt
    this.appendLog(`\x1b[1;32m> ${text}\x1b[0m`);

    // Simulated parser responses
    setTimeout(() => {
      const cleanInput = text.trim().toLowerCase();
      if (cleanInput === '/help') {
        this.appendLog("[Mock Agent] Available commands:");
        this.appendLog("  /help      - List available mock commands.");
        this.appendLog("  /status    - Fetch current agent diagnostic metrics.");
        this.appendLog("  /context   - View loaded staging files.");
        this.appendLog("  /clear     - Flush terminal console buffer.");
      } else if (cleanInput === '/status') {
        this.appendLog("[Mock Agent] Diagnostics:");
        this.appendLog("  - Connection Type: WebSocket gateway (mock)");
        this.appendLog(`  - Active Runtime: ${this.id}`);
        this.appendLog("  - Sandbox State: Healthy (0 warnings)");
      } else if (cleanInput === '/context') {
        this.appendLog("[Mock Agent] Loaded Workspace Context Files:");
        this.appendLog("  - [Mounted] src/app/globals.css (Modified)");
        this.appendLog("  - [Mounted] src/app/page.tsx");
      } else if (cleanInput === '/clear') {
        this.logs = [];
        this.appendLog("\x1b[1;33m[Console Cleared]\x1b[0m");
      } else {
        this.appendLog(`[Mock Agent] Received command: "${text}". Processing...`);
        setTimeout(() => {
          this.appendLog(`[Mock Agent] Done. Task simulated successfully.`);
        }, 1500);
      }
    }, 400);
  }

  getStatus(): RunnerStatus {
    return {
      id: this.id,
      name: this.name,
      type: this.type,
      status: this.status,
      createdAt: this.createdAt,
      logsCount: this.logs.length,
      tokenUsage: this.tokenUsage
    };
  }
}
