/**
 * Radiology Analyzer Integration
 * Ties together DICOM processing and Claude API for automated analysis
 */

import { processDicomSeries } from './dicom-processor.js';
import { buildClaudeRequest, parseAnalysisResponse, estimateTokens } from './claude-radiology-api.js';

/**
 * Main function: Analyze radiology study from current DICOM series
 * @param {Object} options
 * @param {Array} options.folderGroups - Array of {folderName, docIds} objects to keep separate
 * @param {Array} options.docIds - (Deprecated) Array of document IDs for the series
 * @param {string} options.caseContext - Optional case context
 * @param {Function} options.onProgress - Progress callback (0-100)
 * @param {Function} options.onStatus - Status message callback
 * @returns {Promise<Object>} Analysis results
 */
export async function analyzeRadiologyStudy(options) {
  const {
    folderGroups = null,
    docIds = null,
    projectId = null,
    caseContext = null,
    onProgress = () => {},
    onStatus = () => {}
  } = options;

  // Support both new folderGroups and legacy docIds formats
  const usefolderGroups = folderGroups && folderGroups.length > 0;

  if (usefolderGroups) {
    const totalDocIds = folderGroups.reduce((sum, g) => sum + g.docIds.length, 0);
    console.log('[Radiology Analyzer] Starting analysis for', folderGroups.length, 'folder groups with', totalDocIds, 'total docIds');
  } else {
    console.log('[Radiology Analyzer] Starting analysis for', docIds?.length || 0, 'docIds');
  }

  try {
    // Step 1: Process DICOM files
    console.log('[Radiology Analyzer] Step 1: Processing DICOM files...');
    onStatus('Extracting and processing DICOM files...');

    const study = usefolderGroups
      ? await processDicomSeries(folderGroups, (p) => { onProgress(p * 0.4); }, projectId)
      : await processDicomSeries(docIds, (p) => { onProgress(p * 0.4); }, projectId);

    console.log('[Radiology Analyzer] Step 1 complete - study:', study);
    onStatus(`Processed ${study.totalImages} images across ${study.series.length} series`);
    onProgress(40);

    // Step 2: Estimate tokens/cost
    const estimate = estimateTokens(study);
    onStatus(`Estimated cost: $${estimate.estimatedCostUSD} (${estimate.estimatedInputTokens.toLocaleString()} input tokens)`);

    // Step 3: Build Claude request
    console.log('[Radiology Analyzer] Step 3: Building Claude request...');
    onStatus('Building analysis request...');
    const request = buildClaudeRequest(study, { caseContext });

    console.log('[Radiology Analyzer] Request built - message content blocks:', request.messages[0].content.length);
    const imageBlocks = request.messages[0].content.filter(c => c.type === 'image').length;
    console.log('[Radiology Analyzer] Total image blocks in request:', imageBlocks);

    onProgress(50);

    // Step 4: Send to Claude via background script
    console.log('[Radiology Analyzer] Step 4: Sending to Claude...');
    onStatus('Sending to Claude for analysis...');
    const response = await chrome.runtime.sendMessage({
      type: 'ANALYZE_RADIOLOGY',
      request: request
    });

    console.log('[Radiology Analyzer] Received response from Claude');

    if (!response || response.error) {
      throw new Error(response?.error || 'Failed to get analysis from Claude');
    }

    onProgress(90);

    // Step 5: Parse response
    onStatus('Processing analysis results...');
    const analysis = parseAnalysisResponse(response.data);

    onProgress(100);
    onStatus('Analysis complete');

    return {
      success: true,
      study: {
        metadata: study.studyMetadata,
        seriesCount: study.series.length,
        totalImages: study.totalImages
      },
      analysis,
      usage: {
        inputTokens: response.data.usage?.input_tokens,
        outputTokens: response.data.usage?.output_tokens,
        estimatedCost: estimate.estimatedCostUSD
      },
      timestamp: new Date().toISOString()
    };

  } catch (error) {
    console.error('[Radiology Analyzer] Error:', error);
    onStatus(`Error: ${error.message}`);
    return {
      success: false,
      error: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString()
    };
  }
}

/**
 * Quick estimate without full processing
 * Useful for showing user before they commit to analysis
 */
export function quickEstimate(imageCount) {
  const TOKENS_PER_IMAGE = 1600;
  const estimatedTokens = imageCount * TOKENS_PER_IMAGE + 2000;
  const estimatedCost = (estimatedTokens / 1_000_000 * 3.00) + (4000 / 1_000_000 * 15.00);

  return {
    imageCount,
    estimatedTokens,
    estimatedCostUSD: estimatedCost.toFixed(4)
  };
}
