/**
 * Claude API Integration for Radiology Analysis
 * Builds and sends requests to Claude API with DICOM images
 */

/**
 * System prompt for radiology analysis
 */
const RADIOLOGY_SYSTEM_PROMPT = `You are a medical image analysis assistant helping legal professionals understand radiology studies for personal injury litigation. You are NOT providing medical diagnoses—you are describing what is visible in the images to help attorneys understand the medical evidence.

CRITICAL GUIDELINES:
1. Be technically accurate in anatomical descriptions
2. Make findings accessible to non-radiologists
3. Use consistent structure for easy parsing
4. Be explicit about limitations and what requires expert interpretation
5. Never state definitive diagnoses—describe observations objectively
6. Note image quality issues that might affect interpretation

CRITICAL METHODOLOGY - "FIND THE ABSENCE":
This is the most important principle: pathology often presents as the ABSENCE of structures that SHOULD be visible, not as obvious abnormalities.

1. "Find the Absence": For EVERY key structure, explicitly state whether it IS or IS NOT clearly visualized. A structure that should be visible but isn't is a CRITICAL finding. Never skip over a structure just because you "don't see anything wrong."

2. "Expected vs Observed": For each structure, compare what you see to what normal looks like:
   - Expected: what this structure SHOULD look like if normal (signal, shape, position)
   - Observed: what you ACTUALLY see (or don't see)
   - If there's a mismatch, FLAG IT

3. "Internal Comparison": Compare similar structures as reference:
   - Example: "The PCL is well-defined with homogeneous dark signal. The ACL region doesn't show similar characteristics."
   - Use paired structures (left vs right, ACL vs PCL) to establish what normal looks like in THIS patient

4. "Secondary Signs": Look for indirect evidence of injury even if primary structure is equivocal:
   - Bone marrow edema adjacent to attachment sites
   - Joint effusion
   - Soft tissue swelling
   - Altered alignment
   - Muscle edema

5. "Never Assume Normal": Don't call anything normal unless you can DESCRIBE what you see that makes it normal:
   - WRONG: "I don't see anything wrong with the ACL"
   - RIGHT: "The ACL shows dark, taut, parallel fibers from femur to tibia with no signal abnormality"
   - If you can't describe it clearly, it's "Not Clearly Visualized" - which IS a finding

ANALYSIS APPROACH BY MODALITY:

For MRI Studies:
- Identify the pulse sequence (T1, T2, PD, STIR, etc.) and what it highlights
- Note signal intensity changes (hyperintense = bright, hypointense = dark)
- For EVERY key ligament/tendon: Can you trace continuous fibers? If not, state this explicitly
- For EVERY key cartilage surface: Is the surface smooth and intact? If not clearly visible, flag it
- Look for secondary signs: effusion, edema, contusions, altered morphology

For CT Studies:
- Assess bone windows vs soft tissue windows
- Note any fractures, dislocations, or bony abnormalities
- Evaluate soft tissue swelling or hematomas
- Comment on alignment and joint spaces
- For each bone: clearly visible cortex and trabecular pattern?

For X-rays:
- Assess bone alignment and integrity
- Note joint spaces and soft tissue shadows
- Identify any hardware if present
- For each joint space: can you clearly see the joint line?

MANDATORY ASSESSMENT PROCESS:
For EVERY key structure in the imaged region:
1. State whether you CAN or CANNOT clearly identify it
2. If you CAN identify it: describe what makes it appear normal or abnormal
3. If you CANNOT identify it or it's unclear: this is a significant finding that MUST be reported
4. Look for secondary signs that might explain why a structure isn't clearly visible
5. Never skip a structure because you "don't see anything"—absence of clear visualization IS a finding

Always respond with the exact JSON structure specified in the user prompt.`;

/**
 * Build the Claude API request for a DICOM study
 * @param {Object} study - Processed DICOM study from processDicomSeries
 * @param {Object} options - Request options
 * @returns {Object} Claude API request body
 */
export function buildClaudeRequest(study, options = {}) {
  const {
    model = 'claude-sonnet-4-20250514',
    maxTokens = 8192,
    caseContext = null
  } = options;

  const content = [];

  // Add study overview as structured text
  content.push({
    type: 'text',
    text: buildStudyOverviewText(study, caseContext)
  });

  // Add each series with ALL images (no sampling for medical accuracy)
  for (const series of study.series) {
    console.log(`[Claude API] Series "${series.description}": sending all ${series.images.length} images`);

    // Series header
    content.push({
      type: 'text',
      text: `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SERIES: ${series.description}
Sequence Info: ${series.modality} | ${series.totalSlices} total slices | ${series.rows}x${series.columns}
Slice Thickness: ${series.sliceThickness || 'N/A'} mm
Window: C=${series.windowCenter || 'auto'} W=${series.windowWidth || 'auto'}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`
    });

    // Add ALL images for this series (no sampling)
    for (const image of series.images) {
      content.push({
        type: 'image',
        source: {
          type: 'base64',
          media_type: 'image/png',
          data: image.base64
        }
      });

      content.push({
        type: 'text',
        text: `↑ Slice ${image.sliceNumber}/${series.totalSlices}${image.sliceLocation ? ` (Location: ${image.sliceLocation.toFixed(1)}mm)` : ''}`
      });
    }
  }

  // Add the analysis request
  content.push({
    type: 'text',
    text: buildAnalysisRequestText()
  });

  // Debug logging
  const imageCount = content.filter(c => c.type === 'image').length;
  console.log('[Claude API] Built request with', imageCount, 'images across', study.series.length, 'series');
  console.log('[Claude API] Total content blocks:', content.length);

  return {
    model,
    max_tokens: maxTokens,
    system: RADIOLOGY_SYSTEM_PROMPT,
    messages: [{
      role: 'user',
      content
    }]
  };
}

/**
 * Sample images from a series to avoid request size limits
 * Strategy: Include key slices (first, last, middle) plus evenly distributed samples
 * @param {Object} series - Series object with images array
 * @returns {Array} Sampled images array
 */
function sampleSeriesImages(series) {
  const images = series.images;
  const totalImages = images.length;

  // If we have 8 or fewer images, send all
  if (totalImages <= 8) {
    console.log(`[Claude API] Series "${series.description}": sending all ${totalImages} images`);
    return images;
  }

  // For larger series, intelligently sample to ~8 images to keep request size manageable
  // Always include: first, last, and evenly distributed middle slices
  const sampled = [];
  const targetCount = 8;

  // Add first image
  sampled.push(images[0]);

  // Add evenly distributed middle images
  const step = Math.floor((totalImages - 2) / (targetCount - 2));
  for (let i = 1; i < targetCount - 1; i++) {
    const index = i * step;
    if (index < totalImages - 1) {
      sampled.push(images[index]);
    }
  }

  // Add last image
  sampled.push(images[totalImages - 1]);

  console.log(`[Claude API] Series "${series.description}": sampled ${sampled.length} of ${totalImages} images`);
  return sampled;
}

/**
 * Build study overview text
 */
function buildStudyOverviewText(study, caseContext) {
  let text = `RADIOLOGY STUDY FOR ANALYSIS

STUDY INFORMATION:
• Study Type: ${study.studyMetadata.studyDescription || 'Unknown'}
• Modality: ${study.studyMetadata.modality || 'Unknown'}
• Body Part: ${study.studyMetadata.bodyPart || 'Not specified'}
• Institution: ${study.studyMetadata.institution || 'Not specified'}
• Total Series: ${study.series.length}
• Total Images: ${study.totalImages}

SERIES OVERVIEW:
${study.series.map((s, i) => `  ${i + 1}. ${s.description} (${s.totalSlices} slices)`).join('\n')}`;

  if (caseContext) {
    text += `\n\nCASE CONTEXT PROVIDED:
${caseContext}`;
  }

  text += `\n\n${'═'.repeat(60)}
IMAGE DATA FOLLOWS - Each series presented sequentially
${'═'.repeat(60)}`;

  return text;
}

/**
 * Build the analysis request text
 */
function buildAnalysisRequestText() {
  return `

${'═'.repeat(60)}
ANALYSIS REQUEST
${'═'.repeat(60)}

Please analyze this radiology study using the "Find the Absence" methodology and provide your findings in the following JSON structure:

\`\`\`json
{
  "study_summary": {
    "body_part": "string - anatomical region",
    "modality": "string - MRI/CT/X-ray/etc",
    "study_type": "string - e.g., 'Right Knee MRI with standard protocol'",
    "image_quality": "Excellent/Good/Adequate/Limited/Poor",
    "quality_notes": "string - any factors affecting interpretation",
    "series_count": "number",
    "total_images_analyzed": "number"
  },

  "series_analysis": [
    {
      "series_name": "string - from DICOM metadata",
      "sequence_type": "string - e.g., 'T2-weighted FSE', 'PD Fat Sat', 'STIR'",
      "plane": "Axial/Sagittal/Coronal/Oblique",
      "slice_count": "number",
      "what_this_sequence_shows": "string - plain English explanation of what this sequence is designed to visualize",
      "structures_visualized": ["string - list of anatomical structures visible"],
      "observations": "string - detailed description of what is visible, described objectively",
      "signal_characteristics": "string - for MRI: note any abnormal signal patterns",
      "areas_of_note": ["string - any asymmetries, abnormalities, or areas warranting attention"]
    }
  ],

  "anatomical_assessment": {
    "structures_evaluated": {
      "structure_name": {
        "visualization_status": "Clearly Visualized / Partially Visualized / Not Clearly Visualized / Cannot Assess",
        "expected_normal_appearance": "string - what this structure SHOULD look like if normal (signal, morphology, position)",
        "observed_appearance": "string - what you ACTUALLY see in these images",
        "appearance": "Normal/Abnormal/Indeterminate",
        "description": "string - detailed objective description comparing expected vs observed",
        "internal_comparison": "string - comparison to similar/paired structures for reference",
        "secondary_signs_checked": ["string - list of secondary signs evaluated (e.g., 'adjacent bone marrow edema', 'joint effusion')"],
        "concern_level": "None / Low / Moderate / High / Critical",
        "confidence": "High/Moderate/Low"
      }
    }
  },

  "critical_findings": {
    "structures_not_clearly_visualized": [
      {
        "structure": "string - name of structure",
        "clinical_significance": "string - why this matters (e.g., 'ACL tears commonly present as non-visualization of fibers')",
        "expected_visibility": "string - why this structure should be visible on this study",
        "possible_explanations": ["string - possible reasons for non-visualization including pathology"]
      }
    ],
    "secondary_signs_identified": [
      {
        "finding": "string - description of secondary sign",
        "location": "string - anatomical location",
        "suggests": "string - what this finding might indicate"
      }
    ]
  },

  "findings": {
    "primary_observations": ["string - most significant findings including structures NOT clearly visualized"],
    "secondary_observations": ["string - additional notable findings and secondary signs"],
    "normal_findings": ["string - structures that are CLEARLY visualized and appear normal with description"],
    "indeterminate": ["string - findings that cannot be fully assessed and why"]
  },

  "overall_impression": {
    "summary": "string - 2-3 sentence summary emphasizing structures not clearly seen and secondary signs",
    "key_findings": ["string - bullet points of most important observations"],
    "limitations": ["string - what cannot be fully assessed and why"],
    "recommendations": ["string - suggested additional imaging or follow-up if applicable"]
  },

  "litigation_relevance": {
    "structures_commonly_relevant_to_injury": ["string - structures typically at issue in PI cases"],
    "objective_findings_summary": "string - factual summary suitable for legal documentation",
    "questions_for_radiologist": ["string - specific questions especially about structures not clearly visualized"],
    "questions_for_treating_physician": ["string - clinical correlation questions"]
  }
}
\`\`\`

BODY-PART SPECIFIC MANDATORY CHECKLISTS:

For KNEE Studies - You MUST explicitly assess EVERY structure:
□ ACL (Anterior Cruciate Ligament): Can you trace continuous fibers from femur to tibia? Expected: dark, taut fibers
□ PCL (Posterior Cruciate Ligament): Same assessment as ACL - use as internal comparison
□ Medial Meniscus - Anterior Horn: Triangle shape visible? Expected: dark triangular structure
□ Medial Meniscus - Body: Continuous bow-tie appearance?
□ Medial Meniscus - Posterior Horn: Triangle shape visible?
□ Lateral Meniscus - Anterior Horn: Same as medial
□ Lateral Meniscus - Body: Same as medial
□ Lateral Meniscus - Posterior Horn: Same as medial
□ MCL (Medial Collateral Ligament): Dark band along medial joint line?
□ LCL (Lateral Collateral Ligament): Dark band along lateral aspect?
□ Patellar Tendon: Continuous dark band from patella to tibia?
□ Quadriceps Tendon: Continuous dark band proximal to patella?
□ Articular Cartilage - Medial Femoral Condyle: Smooth bright surface?
□ Articular Cartilage - Lateral Femoral Condyle: Same as medial
□ Articular Cartilage - Patella: Smooth surface?
□ Articular Cartilage - Tibial Plateau: Smooth surface?
□ Bone Marrow: Any bright signal on fluid-sensitive sequences suggesting edema/contusion?
□ Joint Effusion: Any bright fluid signal in joint space?
□ Hoffa's Fat Pad: Any edema or mass effect?
□ Baker's Cyst: Any fluid collection in popliteal fossa?

For LUMBAR SPINE Studies - You MUST explicitly assess:
□ Each Intervertebral Disc (L1-L2 through L5-S1): Height, signal intensity, posterior bulge/herniation?
□ Each Neural Foramen (bilateral): Open vs narrowed?
□ Spinal Canal: Central stenosis at each level?
□ Facet Joints: Degenerative changes, effusion, hypertrophy?
□ Vertebral Bodies: Marrow signal, height, alignment, fractures?
□ Posterior Elements: Pars defects, spinous processes?
□ Paraspinal Soft Tissues: Muscle edema, masses?
□ Conus Medullaris: Position and signal?
□ Cauda Equina: Clumping or compression?

For SHOULDER Studies - You MUST explicitly assess:
□ Supraspinatus Tendon: Full thickness visible? Any gaps or bright signal suggesting tear?
□ Infraspinatus Tendon: Same as supraspinatus
□ Subscapularis Tendon: Same as supraspinatus
□ Teres Minor: Same as supraspinatus
□ Long Head Biceps Tendon: Present in groove? Displaced or torn?
□ Superior Labrum: Triangular dark structure? Any detachment?
□ Anterior Labrum: Intact attachment?
□ Posterior Labrum: Intact attachment?
□ Inferior Labrum: Intact attachment?
□ Glenoid Articular Cartilage: Smooth surface?
□ Humeral Head Articular Cartilage: Smooth surface?
□ AC Joint: Alignment, degenerative changes?
□ Subacromial-Subdeltoid Bursa: Fluid or thickening?
□ Bone Marrow: Any edema suggesting impaction or fracture?

For CERVICAL SPINE Studies - You MUST explicitly assess:
□ Each Intervertebral Disc (C2-C3 through C7-T1): Height, signal, herniation?
□ Spinal Cord: Continuous, normal signal, no compression or myelomalacia?
□ Each Neural Foramen (bilateral): Patent vs narrowed?
□ Central Canal: Stenosis at each level?
□ Vertebral Alignment: Normal lordosis vs kyphosis, antero/retrolisthesis?
□ Facet Joints: Degenerative changes?
□ Vertebral Bodies: Marrow signal, fractures?
□ Prevertebral Soft Tissues: Swelling suggesting ligamentous injury?

CRITICAL FINAL REMINDERS:
- For EVERY key structure in the checklist above: explicitly state if it IS or IS NOT clearly visualized
- If you cannot clearly trace a structure that SHOULD be visible: this IS a major finding
- A structure being "not clearly visualized" is MORE significant than seeing something mildly abnormal
- Use internal comparisons: if one meniscus is clear and dark, the other should be too
- Secondary signs matter: bone edema at ACL attachment + ACL not clearly seen = high concern
- Describe observations objectively without diagnosing
- Be specific about location (e.g., "medial compartment", "posterior horn")
- Explain technical terms in parentheses for legal readers
- If image quality limits assessment, say so explicitly
- Distinguish between definite findings and possibilities
- NEVER skip a structure because you "don't see anything wrong" - absence of abnormality ≠ normal`;
}

/**
 * Parse Claude's response to extract the JSON analysis
 * @param {Object} claudeResponse - Raw Claude API response
 * @returns {Object} Parsed analysis object
 */
export function parseAnalysisResponse(claudeResponse) {
  const text = claudeResponse.content[0]?.text || '';

  // Extract JSON from response (handle markdown code blocks)
  const jsonMatch = text.match(/```json\s*([\s\S]*?)\s*```/) ||
                    text.match(/```\s*([\s\S]*?)\s*```/) ||
                    [null, text];

  const jsonString = jsonMatch[1]?.trim();

  if (!jsonString) {
    return {
      raw_response: text,
      parse_error: 'No JSON found in response'
    };
  }

  try {
    return JSON.parse(jsonString);
  } catch (err) {
    return {
      raw_response: text,
      parse_error: `JSON parse error: ${err.message}`
    };
  }
}

/**
 * Estimate token count for the request
 * Useful for cost estimation before sending
 * @param {Object} study - Processed study
 * @returns {Object} Token estimates
 */
export function estimateTokens(study) {
  // Rough estimates based on typical token counts
  const TOKENS_PER_IMAGE = 1600;  // ~1600 tokens per 512x512 PNG
  const TOKENS_PER_TEXT_CHAR = 0.25;  // ~4 chars per token

  const imageTokens = study.totalImages * TOKENS_PER_IMAGE;
  const textTokens = 2000;  // Approximate for metadata and prompts

  const totalInputTokens = imageTokens + textTokens;
  const estimatedOutputTokens = 4000;  // Typical for detailed analysis

  // Pricing as of 2024 (Sonnet 4)
  const inputCostPer1M = 3.00;
  const outputCostPer1M = 15.00;

  const estimatedCost = (totalInputTokens / 1_000_000 * inputCostPer1M) +
                        (estimatedOutputTokens / 1_000_000 * outputCostPer1M);

  return {
    imageCount: study.totalImages,
    estimatedInputTokens: totalInputTokens,
    estimatedOutputTokens,
    estimatedTotalTokens: totalInputTokens + estimatedOutputTokens,
    estimatedCostUSD: estimatedCost.toFixed(4),
    breakdown: {
      imageTokens,
      textTokens
    }
  };
}
