import json
import os

import anthropic

from .prompts import STEP_DETECTION_PROMPT


class RecordingAnalyzer:
    def __init__(self, api_key: str | None = None):
        self.api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")
        if not self.api_key:
            raise ValueError("Anthropic API key is required")
        self.client = anthropic.Anthropic(api_key=self.api_key)

    def analyze_recording(self, events_path: str):
        events = []
        with open(events_path) as f:
            for line in f:
                if line.strip():
                    events.append(json.loads(line))

        # Truncate events if too many (simplification)
        if len(events) > 200:
            events = events[:100] + events[-100:]

        prompt = STEP_DETECTION_PROMPT.format(events_json=json.dumps(events, indent=2))

        response = self.client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=4000,
            messages=[{"role": "user", "content": prompt}],
            response_format={"type": "json_object"},
        )

        content = response.content[0].text
        return json.loads(content)
