/**
 * @file tools/videoTool.js
 * @description Tool for generating videos using AI models (resolved dynamically from backend)
 */

import path from 'path';
import os from 'os';
import { promises as fs } from 'fs';
import { BaseTool } from './baseTool.js';
import { getGalleryService } from '../services/galleryService.js';

/**
 * Configuration constants for video generation.
 *
 * Per-model limits (allowed resolutions, allowed durations, whether
 * variants are supported) are NOT hardcoded here — they live in the
 * model catalog (`video_config` block on each video-generation row) and
 * are enforced authoritatively by the backend route. The CLI sends the
 * request and surfaces the backend's 400 verbatim if the inputs aren't
 * compatible with the chosen model. This keeps the CLI provider-agnostic
 * (Sora 1, Sora 2, future video models all just work) and avoids
 * silently-stale validation tables here.
 *
 * The constants below are CLI-side controls only (queue/concurrency/
 * polling/temp file lifetime/timeout). No model-specific values.
 */
const VIDEO_CONFIG = {
  DEFAULT_MODEL: null,           // resolved dynamically by aiService
  DEFAULT_WIDTH:  1280,          // sensible default; any video model in the
  DEFAULT_HEIGHT: 720,           // catalog with `1280x720` accepts these
  DEFAULT_DURATION: 4,           // Sora 2's smallest unit; safe across providers
  DEFAULT_VARIANTS: 1,           // single video per job (Sora 2; Sora 1 supported up to 4)
  MAX_PROMPT_LENGTH: 4000,
  // Hard CLI safety bounds — let the backend/catalog be authoritative on
  // *which specific values* are allowed for the chosen model, but reject
  // obviously-bogus inputs locally so the user gets immediate feedback.
  ABSOLUTE_MIN_DURATION: 1,
  ABSOLUTE_MAX_DURATION: 60,
  ABSOLUTE_MAX_VARIANTS: 8,
  // Queue + scheduler controls (CLI-side only).
  MAX_CONCURRENT: 2,
  QUEUE_LIMIT: 5,
  POLL_INTERVAL: 5000,           // ms between status checks
  MAX_POLL_TIME: 600000,         // 10 minutes max wait per job
  TEMP_CLEANUP_MS: 86400000,     // 24 h (Sora 2 expires content after 24 h anyway)
  DOWNLOAD_TIMEOUT: 300000       // 5 minutes for video download
};

/**
 * VideoTool - Generate videos using Sora 2 AI model
 * Supports async job-based processing with polling
 */
export class VideoTool extends BaseTool {
  constructor(config = {}, logger = null) {
    super(config, logger);

    // Override tool ID
    this.id = 'video-gen';

    // Job queue and tracking
    this.queue = [];
    this.activeJobs = new Map(); // Currently processing jobs (max 2)
    this.completedJobs = new Map();
    this.isProcessing = false;

    // AIService will be injected later
    this.aiService = null;

    // AgentPool will be injected later (for saving to conversation history)
    this.agentPool = null;

    // Temp directory for videos
    this.tempDir = path.join(os.tmpdir(), 'loxia-videos');

    // Cleanup timers
    this.cleanupTimers = new Map();

    // Polling timers
    this.pollTimers = new Map();
  }

  /**
   * Snapshot of the job state for the web-UI `/api/videos/jobs` endpoint.
   * Serialises the three job maps into a stable JSON shape that the
   * Video Jobs page can render + poll on. Intentionally excludes the
   * large `result` blobs for completed jobs to keep the list light —
   * consumers that want the full result hit the file-serve URL instead.
   *
   * @returns {{
   *   queued: Array<JobSummary>,
   *   active: Array<JobSummary>,
   *   completed: Array<JobSummary>,
   *   limits: { concurrency: number, queue: number },
   * }}
   */
  getJobsSnapshot() {
    const summarize = (j) => ({
      jobId: j.jobId,
      agentId: j.agentId,
      sessionId: j.sessionId,
      prompt: typeof j.prompt === 'string' ? j.prompt.slice(0, 300) : '',
      model: j.model,
      width: j.width,
      height: j.height,
      duration: j.duration,
      variants: j.variants,
      status: j.status || 'unknown',
      soraJobId: j.soraJobId || null,
      outputPath: j.outputPath || null,
      createdAt: j.createdAt || null,
      startedAt: j.startedAt || null,
      completedAt: j.completedAt || null,
      error: j.error || null,
      // Best-effort URL to the final video file if known. The existing
      // /api/videos/:sessionId/:filename serve route locates the file.
      videoUrl: (j.status === 'completed' && j.outputPath && j.sessionId)
        ? `/api/videos/${encodeURIComponent(j.sessionId)}/${encodeURIComponent(
            typeof j.outputPath === 'string' ? j.outputPath.split(/[\\/]/).pop() : ''
          )}`
        : null,
    });
    return {
      queued:    Array.from(this.queue).map(summarize),
      active:    Array.from(this.activeJobs.values()).map(summarize),
      completed: Array.from(this.completedJobs.values()).map(summarize),
      limits: {
        // Was reading the non-existent VIDEO_CONFIG.CONCURRENCY_LIMIT and
        // falling through to `activeJobs.size + queue.length`, which is
        // 0 when idle and produced a misleading `"concurrency": 0` in the
        // /api/videos/jobs snapshot (the real cap is MAX_CONCURRENT=2).
        concurrency: VIDEO_CONFIG?.MAX_CONCURRENT ?? null,
        queue:       VIDEO_CONFIG?.QUEUE_LIMIT    ?? null,
      },
    };
  }

  /**
   * Cancel a video generation job by id. Removes from queue if still
   * pending, marks active jobs for cancellation (best-effort — an
   * in-flight Sora API call will still complete, but we stop polling
   * and stop persisting the result). Returns { success, state }.
   *
   * Completed and already-failed jobs are not cancellable.
   */
  cancelJob(jobId) {
    // Queued — just remove from the queue.
    const qIdx = this.queue.findIndex(j => j.jobId === jobId);
    if (qIdx !== -1) {
      const [job] = this.queue.splice(qIdx, 1);
      job.status = 'cancelled';
      job.completedAt = new Date().toISOString();
      this.completedJobs.set(job.jobId, job);
      this.logger?.info('Video job cancelled (was queued)', { jobId });
      return { success: true, state: 'queued' };
    }
    // Active — mark + stop polling.
    if (this.activeJobs.has(jobId)) {
      const job = this.activeJobs.get(jobId);
      job.status = 'cancelled';
      job.completedAt = new Date().toISOString();
      const timer = this.pollTimers?.get(jobId);
      if (timer) { clearTimeout(timer); this.pollTimers.delete(jobId); }
      this.activeJobs.delete(jobId);
      this.completedJobs.set(jobId, job);
      this.logger?.info('Video job cancelled (was active)', { jobId });
      return { success: true, state: 'active' };
    }
    // Completed / unknown.
    return { success: false, error: 'Job not found or already terminal' };
  }

  /**
   * Set AI service for video generation
   * @param {AIService} aiService - AI service instance
   */
  setAIService(aiService) {
    this.aiService = aiService;
    this.logger?.info('AI Service set for VideoTool');
  }

  /**
   * Set Agent Pool for saving results to conversation history
   * @param {AgentPool} agentPool - AgentPool instance
   */
  setAgentPool(agentPool) {
    this.agentPool = agentPool;
    this.logger?.info('AgentPool set for VideoTool');
  }

  /**
   * Get tool description for agent system prompt
   * @returns {string} Formatted tool description
   */
  getDescription() {
    return `Tool: Video Generator — generate videos from text using the platform's video model.

**Purpose:** Generate short videos from text descriptions. Videos are saved to disk and made available in chat. The active video model is resolved automatically from the model catalog (currently Sora 2 on this deployment); model-specific limits like allowed resolutions and durations come from the catalog and are enforced by the backend.

**CRITICAL: Automatic Execution**
- ANY \`\`\`json block with "toolId": "video-gen" will be EXECUTED IMMEDIATELY.
- Just output the command when you want to generate a video.
- Video generation takes minutes — a job ID is returned immediately and the file lands when the job finishes.

**USAGE:**
\`\`\`json
{
  "toolId": "video-gen",
  "parameters": {
    "prompt": "Detailed description of the video",
    "outputPath": "videos/filename.mp4",
    "width": 1280,
    "height": 720,
    "duration": 4
  }
}
\`\`\`

**Parameters:**
- **prompt** (required): Detailed description of the video.
- **outputPath** (optional): Where to save the .mp4 (permanent). Omit for a temp file.
- **width** / **height** (optional): Resolution. The catalog defines allowed pairs per model; the backend rejects unsupported pairs with a clear 400 listing valid values.
- **duration** (optional): Duration in seconds. The catalog defines allowed values per model.
- **variants** (optional): Number of video variants. Some models (e.g. Sora 2) only return one video per job; the backend will reject \`variants > 1\` with a clear message naming the model's limit.
- **model** (optional): Override the auto-resolved model. Must be a video-generation model in the catalog.

**Current model limits (Sora 2):**
- Resolutions: \`720x1280\`, \`1280x720\`, \`1024x1792\`, \`1792x1024\` (16:9 / 9:16 only — no square or 480p)
- Durations: \`4\`, \`8\`, or \`12\` seconds (those exact values, no others)
- Variants: 1 per job — request multiple separately if you need more

These limits live in the catalog row, not in this tool. If the model rotates (e.g. Sora 3) or a new video model is added, the allowed values update automatically and you'll see them in the backend's 400 if you submit unsupported inputs.

**EXAMPLE:**
User: "create a video of a cat playing"
You output:
\`\`\`json
{
  "toolId": "video-gen",
  "parameters": {
    "prompt": "A fluffy orange tabby cat with white paws crouches low on a sunlit hardwood floor, eyes locked on a red laser dot. The cat pounces forward, slides slightly on the polished wood, then quickly pivots to chase the dot as it darts away. Warm afternoon sunlight streams through sheer curtains, casting soft golden highlights on the cat's fur. Cozy living room with a beige sofa in the background.",
    "outputPath": "videos/cat-playing.mp4",
    "width": 1280,
    "height": 720,
    "duration": 4
  }
}
\`\`\`

**Prompt Guidelines (IMPORTANT):**
Sora simulates a physical world — write prompts as narratives, not camera commands. Use the CAST method: describe the **Character** (appearance, clothing, posture), **Action** (broken into beats: "takes three steps, pauses, looks back"), **Setting** (time of day, weather, specific objects), and **Tone/Atmosphere** (lighting quality, color palette, mood). Be specific and sensory — replace "beautiful street" with "rain-slick Tokyo asphalt reflecting neon signs." Keep prompts under 120 words, focus on ONE action per clip, and use simple camera cues only if needed ("wide shot," "close-up"). Anchor lighting explicitly ("warm golden hour sunlight with soft shadows") and name colors (teal, amber, magenta) for palette consistency. For character consistency across clips, repeat the same distinctive details (clothing colors, accessories, features) in each prompt. Avoid real people, copyrighted characters, and sensitive content.

**Notes:**
- Videos take 1-3 minutes to generate (Sora 2 short clips).
- Max ${VIDEO_CONFIG.QUEUE_LIMIT} videos in queue, max ${VIDEO_CONFIG.MAX_CONCURRENT} concurrent jobs.
- Generated videos expire on the provider after 24 hours; if you need to keep them, set an \`outputPath\` so the local copy persists.`;
  }

  /**
   * Parse video generation parameters
   * @param {string|Object} content - Raw content or parsed object
   * @returns {Object} Parsed parameters
   */
  parseParameters(content) {
    // Handle JSON format
    if (typeof content === 'object' && content !== null) {
      return this._parseJSONParams(content);
    }

    // Handle string format
    if (typeof content === 'string') {
      const trimmed = content.trim();

      // Try to parse as JSON first
      if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
        try {
          const parsed = JSON.parse(trimmed);
          return this._parseJSONParams(parsed);
        } catch (err) {
          // Not valid JSON, fall through to XML parsing
        }
      }

      // Parse as XML
      return this._parseXMLParams(content);
    }

    throw new Error('Invalid parameter format');
  }

  /**
   * Parse JSON parameters
   * @private
   */
  _parseJSONParams(obj) {
    // Handle parameters wrapper (when called via toolId/parameters structure)
    if (obj.parameters) {
      obj = obj.parameters;
    }

    // Check for batch mode
    if (obj.batch && Array.isArray(obj.batch)) {
      return {
        batch: true,
        videos: obj.batch.map(vid => this._parseVideoParams(vid))
      };
    }

    return {
      batch: false,
      videos: [this._parseVideoParams(obj)]
    };
  }

  /**
   * Parse XML parameters
   * @private
   */
  _parseXMLParams(content) {
    const params = { batch: false, videos: [] };

    // Check for batch mode
    const batchMatch = /<batch>([\s\S]*?)<\/batch>/i.exec(content);

    if (batchMatch) {
      params.batch = true;
      const batchContent = batchMatch[1];

      // Extract individual <video> blocks
      const videoRegex = /<video>([\s\S]*?)<\/video>/gi;
      let match;

      while ((match = videoRegex.exec(batchContent)) !== null) {
        params.videos.push(this._parseXMLVideo(match[1]));
      }
    } else {
      // Single video mode
      params.videos.push(this._parseXMLVideo(content));
    }

    if (params.videos.length === 0) {
      throw new Error('No valid video parameters found');
    }

    return params;
  }

  /**
   * Parse single video parameters from object
   * @private
   */
  _parseVideoParams(obj) {
    const outputPath = obj.outputPath || obj['output-path'] || null;

    return {
      prompt: obj.prompt || '',
      outputPath: outputPath,
      saveToProject: outputPath !== null,
      model: obj.model || VIDEO_CONFIG.DEFAULT_MODEL,
      width: parseInt(obj.width) || VIDEO_CONFIG.DEFAULT_WIDTH,
      height: parseInt(obj.height) || VIDEO_CONFIG.DEFAULT_HEIGHT,
      duration: parseInt(obj.duration) || VIDEO_CONFIG.DEFAULT_DURATION,
      variants: parseInt(obj.variants) || VIDEO_CONFIG.DEFAULT_VARIANTS
    };
  }

  /**
   * Parse single video parameters from XML string
   * @private
   */
  _parseXMLVideo(xmlContent) {
    const extractTag = (tag) => {
      const regex = new RegExp(`<${tag}>([\\s\\S]*?)<\\/${tag}>`, 'i');
      const match = regex.exec(xmlContent);
      return match ? match[1].trim() : null;
    };

    const outputPath = extractTag('output-path') || null;

    return {
      prompt: extractTag('prompt') || '',
      outputPath: outputPath,
      saveToProject: outputPath !== null,
      model: extractTag('model') || VIDEO_CONFIG.DEFAULT_MODEL,
      width: parseInt(extractTag('width')) || VIDEO_CONFIG.DEFAULT_WIDTH,
      height: parseInt(extractTag('height')) || VIDEO_CONFIG.DEFAULT_HEIGHT,
      duration: parseInt(extractTag('duration')) || VIDEO_CONFIG.DEFAULT_DURATION,
      variants: parseInt(extractTag('variants')) || VIDEO_CONFIG.DEFAULT_VARIANTS
    };
  }

  /**
   * Execute video generation
   * @param {Object|string} params - Parsed parameters object OR raw XML/JSON string
   * @param {Object} context - Execution context
   * @returns {Promise<Object>} Execution result
   */
  async execute(params, context = {}) {
    try {
      const { agentId, projectDir, directoryAccess, sessionId } = context;

      // Auto-detect and parse inputs
      if (typeof params === 'string') {
        this.logger?.info('VideoTool: Auto-parsing string parameters');
        params = this.parseParameters(params);
      } else if (typeof params === 'object' && params !== null && !params.videos) {
        this.logger?.info('VideoTool: Normalizing object parameters');
        params = this.parseParameters(params);
      }

      // Validate parameters
      this._validateParameters(params);

      // Queue videos
      const jobIds = [];

      for (const videoParams of params.videos) {
        // Create job
        const jobId = this._generateJobId();

        const job = {
          jobId,
          agentId,
          sessionId,
          prompt: videoParams.prompt,
          outputPath: videoParams.outputPath,
          saveToProject: videoParams.saveToProject,
          model: videoParams.model,
          width: videoParams.width,
          height: videoParams.height,
          duration: videoParams.duration,
          variants: videoParams.variants,
          projectDir: projectDir || process.cwd(),
          directoryAccess,
          // Per-agent video-gen config (reaches the async processor
          // through the job). Used to gate `saveToGallery` below.
          toolConfig: context?.toolConfig || null,
          status: 'queued',
          soraJobId: null, // Will be set when submitted to Sora
          createdAt: new Date().toISOString()
        };

        // Check queue limit
        if (this.queue.length >= VIDEO_CONFIG.QUEUE_LIMIT) {
          return {
            success: false,
            error: `Queue limit reached (${VIDEO_CONFIG.QUEUE_LIMIT} videos). Please wait for current jobs to complete.`,
            queueLength: this.queue.length
          };
        }

        this.queue.push(job);
        jobIds.push(jobId);

        this.logger?.info(`Video generation job queued: ${jobId}`, {
          prompt: videoParams.prompt.substring(0, 50) + '...',
          queuePosition: this.queue.length
        });
      }

      // Start processing if not already running
      if (!this.isProcessing) {
        this._processQueue().catch(err => {
          this.logger?.error('Queue processing error:', err);
        });
      }

      // Return immediate response
      return {
        success: true,
        jobIds,
        queueLength: this.queue.length,
        activeJobs: this.activeJobs.size,
        message: params.batch
          ? `${jobIds.length} videos queued for generation`
          : 'Video queued for generation',
        estimatedWaitTime: this._estimateWaitTime()
      };

    } catch (error) {
      this.logger?.error('Video generation error:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Sanity-check inputs before submitting to the backend. Per-model limits
   * (which exact resolutions and durations a given video model accepts)
   * are NOT enforced here — the catalog declares them and the backend
   * route validates against the catalog row. This keeps the CLI
   * provider-agnostic; if the inputs aren't compatible with the chosen
   * model, the backend's 400 surfaces back through the queue's `error`
   * field with a clear message naming the allowed values.
   *
   * Local checks below cover only "obviously wrong" inputs that no video
   * provider would accept — empty prompts, non-positive dimensions, etc.
   *
   * @private
   */
  _validateParameters(params) {
    if (!params.videos || params.videos.length === 0) {
      throw new Error('No videos specified');
    }

    for (const vid of params.videos) {
      if (!vid.prompt || vid.prompt.trim().length === 0) {
        throw new Error('Video prompt is required');
      }
      if (vid.prompt.length > VIDEO_CONFIG.MAX_PROMPT_LENGTH) {
        throw new Error(`Prompt too long (max ${VIDEO_CONFIG.MAX_PROMPT_LENGTH} characters)`);
      }

      // Width/height must be positive integers — backend + provider
      // decide which exact pairs are valid for the chosen model.
      if (vid.width != null && (!Number.isInteger(vid.width) || vid.width <= 0)) {
        throw new Error(`Invalid width: ${vid.width}. Must be a positive integer.`);
      }
      if (vid.height != null && (!Number.isInteger(vid.height) || vid.height <= 0)) {
        throw new Error(`Invalid height: ${vid.height}. Must be a positive integer.`);
      }

      // Duration: only catch absurd values here; the catalog declares
      // the per-model allowed list (e.g. Sora 2: {4, 8, 12} seconds).
      if (vid.duration != null) {
        if (typeof vid.duration !== 'number' || vid.duration < VIDEO_CONFIG.ABSOLUTE_MIN_DURATION || vid.duration > VIDEO_CONFIG.ABSOLUTE_MAX_DURATION) {
          throw new Error(`Invalid duration: ${vid.duration}. Must be a number between ${VIDEO_CONFIG.ABSOLUTE_MIN_DURATION} and ${VIDEO_CONFIG.ABSOLUTE_MAX_DURATION} seconds. The chosen model may support a narrower set — see /llm/models.`);
        }
      }

      // Variants: same approach — sanity-only. Some models (e.g. Sora 2)
      // only return a single video per job; the backend will 400 if the
      // model doesn't support multiple variants.
      if (vid.variants != null) {
        if (!Number.isInteger(vid.variants) || vid.variants < 1 || vid.variants > VIDEO_CONFIG.ABSOLUTE_MAX_VARIANTS) {
          throw new Error(`Invalid variants: ${vid.variants}. Must be an integer between 1 and ${VIDEO_CONFIG.ABSOLUTE_MAX_VARIANTS}. The chosen model may only support 1.`);
        }
      }

      if (vid.outputPath) {
        const ext = path.extname(vid.outputPath).toLowerCase();
        if (ext && ext !== '.mp4') {
          throw new Error(`Invalid format: ${ext}. Only .mp4 is supported`);
        }
      }
    }
  }

  /**
   * Process the video generation queue
   * @private
   */
  async _processQueue() {
    if (this.isProcessing) {
      return;
    }

    this.isProcessing = true;

    while (this.queue.length > 0 || this.activeJobs.size > 0) {
      // Start new jobs if under concurrent limit
      while (this.queue.length > 0 && this.activeJobs.size < VIDEO_CONFIG.MAX_CONCURRENT) {
        const job = this.queue.shift();
        await this._startVideoJob(job);
      }

      // Wait a bit before checking again
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    this.isProcessing = false;
  }

  /**
   * Start a video generation job
   * @private
   */
  async _startVideoJob(job) {
    this.logger?.info(`Starting video generation job: ${job.jobId}`);

    try {
      job.status = 'submitting';

      // Check if AI service is available
      if (!this.aiService) {
        throw new Error('AI service not available. Video generation requires AI service.');
      }

      // Submit to Sora API
      const options = {
        width: job.width,
        height: job.height,
        duration: job.duration,
        variants: job.variants,
        sessionId: job.sessionId
      };

      const result = await this.aiService.generateVideo(job.prompt, options);

      // Store Sora job ID
      job.soraJobId = result.jobId;
      job.status = 'processing';
      job.submittedAt = new Date().toISOString();

      // Add to active jobs
      this.activeJobs.set(job.jobId, job);

      this.logger?.info(`Video job submitted to Sora: ${job.soraJobId}`, {
        localJobId: job.jobId
      });

      // Broadcast status update
      this._broadcastJobStatus(job, 'processing', 'Video generation started');

      // Start polling for completion
      this._pollJobStatus(job);

    } catch (error) {
      this.logger?.error(`Failed to start video job: ${job.jobId}`, error);

      job.status = 'failed';
      job.error = error.message;
      job.completedAt = new Date().toISOString();

      this.completedJobs.set(job.jobId, job);

      // Broadcast error
      this._broadcastJobStatus(job, 'failed', error.message);
    }
  }

  /**
   * Poll for job completion
   * @private
   */
  async _pollJobStatus(job) {
    const startTime = Date.now();

    const poll = async () => {
      try {
        // Check if we've exceeded max poll time
        if (Date.now() - startTime > VIDEO_CONFIG.MAX_POLL_TIME) {
          throw new Error('Video generation timeout - exceeded maximum wait time');
        }

        // Get status from Sora - pass sessionId for API key retrieval
        const status = await this.aiService.getVideoJobStatus(job.soraJobId, {
          sessionId: job.sessionId,
          model: job.model
        });

        this.logger?.debug(`Video job status: ${status.status}`, {
          jobId: job.jobId,
          soraJobId: job.soraJobId,
          sessionId: job.sessionId
        });

        if (status.status === 'succeeded' || status.status === 'completed') {
          // Job completed successfully
          await this._handleJobComplete(job, status);
        } else if (status.status === 'failed' || status.status === 'cancelled') {
          // Job failed
          throw new Error(status.error || 'Video generation failed');
        } else {
          // Still processing - poll again
          const timer = setTimeout(() => poll(), VIDEO_CONFIG.POLL_INTERVAL);
          this.pollTimers.set(job.jobId, timer);
        }
      } catch (error) {
        this.logger?.error(`Video job failed: ${job.jobId}`, error);
        await this._handleJobFailed(job, error);
      }
    };

    // Start polling
    poll();
  }

  /**
   * Handle successful job completion
   * @private
   */
  async _handleJobComplete(job, status) {
    this.logger?.info(`Video generation completed: ${job.jobId}`);

    try {
      // Clear poll timer
      const timer = this.pollTimers.get(job.jobId);
      if (timer) {
        clearTimeout(timer);
        this.pollTimers.delete(job.jobId);
      }

      // Remove from active jobs
      this.activeJobs.delete(job.jobId);

      // Get generation ID from status - Sora returns generation ID, not direct URL
      const generationId = status.generationId || status.generations?.[0]?.id;

      if (!generationId) {
        throw new Error('No generation ID received from Sora');
      }

      // Construct video download URL through our backend proxy
      // The backend will authenticate with Sora and stream the video
      const backendUrl = this.aiService?.baseUrl || process.env.LOXIA_BACKEND_URL || 'http://localhost:3001';
      const videoUrl = `${backendUrl}/llm/video-content/${generationId}?model=${job.model || ''}`;

      this.logger?.info(`Video content URL: ${videoUrl}`, { generationId });

      // Resolve output path and download
      const resolvedOutputPath = await this._resolveOutputPath(job);

      let savedToDisk = false;
      let downloadError = null;

      try {
        await fs.mkdir(path.dirname(resolvedOutputPath), { recursive: true });
        await this._downloadVideo(videoUrl, resolvedOutputPath, job.sessionId);
        savedToDisk = true;

        // Schedule cleanup if temp file
        if (!job.saveToProject) {
          this._scheduleCleanup(resolvedOutputPath, job.jobId);
        }
      } catch (err) {
        downloadError = err.message;
        this.logger?.warn(`Failed to save video to disk: ${err.message}`);
      }

      job.status = 'completed';
      job.result = {
        jobId: job.jobId,
        soraJobId: job.soraJobId,
        prompt: job.prompt,
        outputPath: job.outputPath,
        resolvedOutputPath: savedToDisk ? resolvedOutputPath : null,
        temporaryUrl: videoUrl,
        savedToDisk,
        downloadError,
        success: true,
        model: job.model,
        width: job.width,
        height: job.height,
        duration: job.duration,
        generations: status.generations || []
      };
      job.completedAt = new Date().toISOString();

      this.completedJobs.set(job.jobId, job);

      // Durable gallery copy — non-blocking, non-fatal. Skipped when
      // the agent has opted out via `toolConfig.video-gen.saveToGallery`.
      if (savedToDisk && resolvedOutputPath && job.toolConfig?.saveToGallery !== false) {
        try {
          let agentName = null;
          if (this.agentPool && job.agentId) {
            try {
              const a = await this.agentPool.getAgent(job.agentId);
              agentName = a?.name || null;
            } catch { /* non-fatal */ }
          }
          await getGalleryService(this.logger).saveVideo({
            sourcePath: resolvedOutputPath,
            metadata: {
              prompt: job.prompt,
              model: job.model,
              width: job.width,
              height: job.height,
              duration: job.duration,
              variants: job.variants,
              agentId: job.agentId,
              agentName,
              sessionId: job.sessionId,
              jobId: job.jobId,
              soraJobId: job.soraJobId,
              createdAt: job.completedAt,
            },
          });
        } catch (galErr) {
          this.logger?.warn?.('Gallery save failed (non-fatal)', {
            jobId: job.jobId,
            error: galErr.message,
          });
        }
      }

      // Broadcast success
      this._broadcastJobResult(job, savedToDisk ? resolvedOutputPath : null, videoUrl, savedToDisk);

      // Save to conversation history
      await this._saveToConversationHistory(job, false);

    } catch (error) {
      this.logger?.error(`Error handling job completion: ${job.jobId}`, error);
      await this._handleJobFailed(job, error);
    }
  }

  /**
   * Handle job failure
   * @private
   */
  async _handleJobFailed(job, error) {
    // Clear poll timer
    const timer = this.pollTimers.get(job.jobId);
    if (timer) {
      clearTimeout(timer);
      this.pollTimers.delete(job.jobId);
    }

    // Remove from active jobs
    this.activeJobs.delete(job.jobId);

    job.status = 'failed';
    job.error = error.message;
    job.completedAt = new Date().toISOString();

    this.completedJobs.set(job.jobId, job);

    // Broadcast error
    this._broadcastJobStatus(job, 'failed', error.message);

    // Save error to conversation history
    await this._saveToConversationHistory(job, true);
  }

  /**
   * Broadcast job status update
   * @private
   */
  _broadcastJobStatus(job, status, message) {
    if (global.loxiaWebServer && job.sessionId) {
      global.loxiaWebServer.broadcastToSession(job.sessionId, {
        type: 'videoJobStatus',
        agentId: job.agentId,
        jobId: job.jobId,
        soraJobId: job.soraJobId,
        status,
        message,
        prompt: job.prompt,
        timestamp: new Date().toISOString()
      });
    }
  }

  /**
   * Broadcast job result
   * @private
   */
  _broadcastJobResult(job, localPath, videoUrl, savedToDisk) {
    this.logger?.info('📢 Broadcasting video result', {
      jobId: job.jobId,
      savedToDisk,
      localPath,
      originalVideoUrl: videoUrl,
      hasWebServer: !!global.loxiaWebServer,
      sessionId: job.sessionId
    });

    if (global.loxiaWebServer && job.sessionId) {
      // Convert to web URL if saved locally
      let webUrl = videoUrl;
      if (savedToDisk && localPath) {
        webUrl = this._convertToWebUrl(localPath, job.sessionId);
      }

      global.loxiaWebServer.broadcastToSession(job.sessionId, {
        type: 'videoGenerated',
        agentId: job.agentId,
        jobId: job.jobId,
        soraJobId: job.soraJobId,
        videoUrl: webUrl,
        localPath,
        prompt: job.prompt,
        success: true,
        savedToDisk,
        isTemporary: !savedToDisk,
        width: job.width,
        height: job.height,
        duration: job.duration,
        timestamp: job.completedAt
      });

      this.logger?.info('Video generation broadcast sent', {
        jobId: job.jobId,
        savedToDisk
      });
    }
  }

  /**
   * Save result to conversation history
   * @private
   */
  async _saveToConversationHistory(job, isError) {
    if (!this.agentPool || !job.agentId) {
      return;
    }

    try {
      const agent = await this.agentPool.getAgent(job.agentId);
      if (!agent) {
        return;
      }

      let message;

      if (isError) {
        message = {
          id: `vid-error-${job.jobId}`,
          role: 'system',
          content: `Video generation failed: ${job.error}\n\n**Prompt:** ${job.prompt}`,
          timestamp: job.completedAt,
          type: 'error',
          toolId: 'video-gen',
          status: 'failed',
          jobId: job.jobId
        };
      } else {
        let content = `Video generated: ${job.prompt}`;

        if (!job.result.savedToDisk) {
          content += '\n\nWarning: Video is using a temporary URL (expires in ~24 hours).';
          if (job.result.downloadError) {
            content += `\n**Error:** ${job.result.downloadError}`;
          }
        }

        message = {
          id: `vid-result-${job.jobId}`,
          role: 'assistant',
          content,
          timestamp: job.completedAt,
          // Use persistent URL (session-independent) for conversation history
          // This allows videos to work after restart
          videoUrl: job.result.savedToDisk
            ? this._convertToPersistentUrl(job.persistentFilename || path.basename(job.result.resolvedOutputPath))
            : job.result.temporaryUrl,
          // Also store filename for fallback lookups
          videoFilename: job.persistentFilename || (job.result.resolvedOutputPath ? path.basename(job.result.resolvedOutputPath) : null),
          type: 'video-result',
          toolId: 'video-gen',
          status: 'completed',
          isTemporary: !job.result.savedToDisk,
          savedToDisk: job.result.savedToDisk,
          width: job.width,
          height: job.height,
          duration: job.duration
        };
      }

      // Add to full conversation
      agent.conversations.full.messages.push(message);
      agent.conversations.full.lastUpdated = job.completedAt;

      // Add to current model conversation if exists
      if (agent.currentModel && agent.conversations[agent.currentModel]) {
        agent.conversations[agent.currentModel].messages.push(message);
        agent.conversations[agent.currentModel].lastUpdated = job.completedAt;
      }

      agent.lastActivity = job.completedAt;

      await this.agentPool.persistAgentState(job.agentId);

      this.logger?.info('Video result saved to conversation history', {
        agentId: job.agentId,
        jobId: job.jobId,
        isError
      });

      // Queue tool result so agent "sees" the completion/failure and can continue
      if (isError) {
        await this.agentPool.addToolResult(job.agentId, {
          toolId: 'video-gen',
          status: 'failed',
          error: job.error,
          result: {
            jobId: job.jobId,
            prompt: job.prompt
          },
          timestamp: job.completedAt
        });
      } else {
        await this.agentPool.addToolResult(job.agentId, {
          toolId: 'video-gen',
          status: 'completed',
          result: {
            jobId: job.jobId,
            prompt: job.prompt,
            videoUrl: message.videoUrl,
            localPath: job.result.resolvedOutputPath,
            savedToDisk: job.result.savedToDisk,
            isTemporary: !job.result.savedToDisk,
            width: job.width,
            height: job.height,
            duration: job.duration
          },
          timestamp: job.completedAt
        });
      }

      this.logger?.info('Video result queued for agent processing', {
        agentId: job.agentId,
        jobId: job.jobId,
        isError
      });

    } catch (error) {
      this.logger?.error('Failed to save video result to conversation history', {
        error: error.message,
        agentId: job.agentId,
        jobId: job.jobId
      });
    }
  }

  /**
   * Resolve output path - save to agent's working directory for persistence
   * @private
   */
  async _resolveOutputPath(job) {
    // Use agent's working directory from directoryAccess settings
    // Fall back to projectDir, then cwd
    const workingDir = job.directoryAccess?.workingDirectory || job.projectDir || process.cwd();
    const videosDir = path.join(workingDir, 'generated-videos');

    // Create videos directory
    await fs.mkdir(videosDir, { recursive: true });

    let filename;
    if (job.outputPath) {
      // User specified a path - use it if within working directory
      if (path.isAbsolute(job.outputPath)) {
        // Absolute path - validate it's within working directory
        const normalizedPath = path.normalize(job.outputPath);
        if (!normalizedPath.startsWith(path.normalize(workingDir))) {
          throw new Error('Output path must be within agent working directory');
        }
        // Use the full path, create parent dirs
        await fs.mkdir(path.dirname(normalizedPath), { recursive: true });
        job.saveToProject = true;
        job.persistentFilename = path.basename(normalizedPath);
        return normalizedPath;
      } else {
        // Relative path - resolve relative to working directory
        const resolvedPath = path.normalize(path.join(workingDir, job.outputPath));
        if (!resolvedPath.startsWith(path.normalize(workingDir))) {
          throw new Error('Path traversal detected');
        }
        await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
        job.saveToProject = true;
        job.persistentFilename = path.basename(resolvedPath);
        return resolvedPath;
      }
    } else {
      // Generate filename from job ID in generated-videos folder
      filename = `video-${job.jobId}.mp4`;
    }

    const resolvedPath = path.join(videosDir, filename);

    this.logger?.info('📁 Video will be saved to agent directory', {
      workingDir,
      filename,
      resolvedPath
    });

    // Mark job as saved to project for correct URL generation
    job.saveToProject = true;
    job.persistentFilename = filename;

    return resolvedPath;
  }

  /**
   * Download video from URL
   * @private
   */
  async _downloadVideo(videoUrl, outputPath, sessionId) {
    try {
      // Get API key for authentication with backend
      let apiKey = null;
      if (this.aiService?.apiKeyManager) {
        const keys = this.aiService.apiKeyManager.getKeysForRequest(null);
        apiKey = keys.loxiaApiKey;
      }
      if (!apiKey) {
        apiKey = process.env.LOXIA_API_KEY;
      }

      const headers = {};
      if (apiKey) {
        headers['Authorization'] = `Bearer ${apiKey}`;
      }

      this.logger?.info('📥 Downloading video', {
        url: videoUrl,
        hasApiKey: !!apiKey,
        apiKeySource: apiKey ? (this.aiService?.apiKeyManager ? 'apiKeyManager' : 'env') : 'none',
        outputPath,
        sessionId
      });

      const response = await fetch(videoUrl, {
        headers,
        signal: AbortSignal.timeout(VIDEO_CONFIG.DOWNLOAD_TIMEOUT)
      });

      if (!response.ok) {
        const errorText = await response.text().catch(() => '');
        throw new Error(`Failed to download video: HTTP ${response.status} - ${errorText}`);
      }

      const buffer = Buffer.from(await response.arrayBuffer());
      await fs.writeFile(outputPath, buffer);

      this.logger?.info(`Video saved to: ${outputPath}`);

    } catch (error) {
      this.logger?.error('❌ Video download failed', {
        errorName: error.name,
        errorMessage: error.message,
        url: videoUrl,
        outputPath
      });

      if (error.name === 'TimeoutError') {
        throw new Error('Video download timeout');
      } else if (error.name === 'TypeError') {
        throw new Error(`Network error: ${error.message}`);
      } else {
        throw new Error(`Download failed: ${error.message}`);
      }
    }
  }

  /**
   * Schedule cleanup of temp file
   * @private
   */
  _scheduleCleanup(filePath, jobId) {
    const timer = setTimeout(async () => {
      try {
        await fs.unlink(filePath);
        this.logger?.debug(`Cleaned up temp video: ${filePath}`);
        this.cleanupTimers.delete(jobId);
      } catch (error) {
        // File might already be deleted, ignore
      }
    }, VIDEO_CONFIG.TEMP_CLEANUP_MS);

    this.cleanupTimers.set(jobId, timer);
  }

  /**
   * Convert local file path to web-accessible URL
   * @private
   */
  _convertToWebUrl(localPath, sessionId) {
    const filename = path.basename(localPath);
    const port = global.loxiaWebServer?.port || 8080;
    let host = global.loxiaWebServer?.host || 'localhost';

    if (host === '0.0.0.0') {
      host = 'localhost';
    }

    const webUrl = `http://${host}:${port}/api/videos/${sessionId}/${filename}`;

    this.logger?.info('🔗 Converting local path to web URL', {
      localPath,
      sessionId,
      webUrl
    });

    return webUrl;
  }

  /**
   * Convert filename to persistent (session-independent) URL
   * These URLs work after browser refresh and system restart
   * @private
   */
  _convertToPersistentUrl(filename) {
    const port = global.loxiaWebServer?.port || 8080;
    let host = global.loxiaWebServer?.host || 'localhost';

    if (host === '0.0.0.0') {
      host = 'localhost';
    }

    // Use the session-independent endpoint that searches all agent directories
    const persistentUrl = `http://${host}:${port}/api/generated-videos/${filename}`;

    this.logger?.info('🔗 Generated persistent URL for video', {
      filename,
      persistentUrl
    });

    return persistentUrl;
  }

  /**
   * Estimate wait time based on queue
   * @private
   */
  _estimateWaitTime() {
    const avgGenerationTime = 300; // 5 minutes in seconds
    const queuePosition = this.queue.length;
    const activeJobs = this.activeJobs.size;

    if (queuePosition === 0 && activeJobs === 0) {
      return '~5 minutes';
    }

    // Calculate based on queue position and concurrent limit
    const waitingJobs = queuePosition + activeJobs;
    const batches = Math.ceil(waitingJobs / VIDEO_CONFIG.MAX_CONCURRENT);
    const estimatedSeconds = batches * avgGenerationTime;

    const minutes = Math.floor(estimatedSeconds / 60);

    if (minutes >= 60) {
      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;
      return `~${hours}h ${remainingMinutes}m`;
    }

    return `~${minutes} minutes`;
  }

  /**
   * Generate unique job ID
   * @private
   */
  _generateJobId() {
    return `vid-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
  }

  /**
   * Get job status
   * @param {string} jobId - Job ID
   * @returns {Object} Job status
   */
  getJobStatus(jobId) {
    // Check completed jobs
    if (this.completedJobs.has(jobId)) {
      return this.completedJobs.get(jobId);
    }

    // Check active jobs
    if (this.activeJobs.has(jobId)) {
      return this.activeJobs.get(jobId);
    }

    // Check queue
    const queuedJob = this.queue.find(job => job.jobId === jobId);
    if (queuedJob) {
      return queuedJob;
    }

    return {
      jobId,
      status: 'not_found'
    };
  }

  /**
   * Cleanup on shutdown
   */
  async cleanup() {
    this.logger?.info('Shutting down VideoTool');

    // Clear all cleanup timers
    for (const timer of this.cleanupTimers.values()) {
      clearTimeout(timer);
    }
    this.cleanupTimers.clear();

    // Clear all poll timers
    for (const timer of this.pollTimers.values()) {
      clearTimeout(timer);
    }
    this.pollTimers.clear();

    // Mark queued jobs as cancelled
    for (const job of this.queue) {
      job.status = 'cancelled';
    }
    this.queue = [];

    // Mark active jobs as cancelled
    for (const job of this.activeJobs.values()) {
      job.status = 'cancelled';
    }
    this.activeJobs.clear();
  }
}

export default VideoTool;
