import os
from django.conf import settings


class StorageService:
    def build_call_audio_filename(self, call):
        created_at_str = call.created_at.strftime('%Y%m%d_%H%M%S')
        return f"call_recording_{call.call_id}_{created_at_str}.mp3"

    def call_recording_local_path(self, filename):
        relative_path = os.path.join("call_recordings", filename)
        absolute_path = os.path.join(settings.MEDIA_ROOT, relative_path)
        return relative_path, absolute_path

    def call_recording_public_url(self, request, relative_path):
        return request.build_absolute_uri(settings.MEDIA_URL + relative_path).replace("http://", "https://")

    def save_call_recording_stream(self, filepath, response_stream):
        os.makedirs(os.path.dirname(filepath), exist_ok=True)
        with open(filepath, "wb") as f:
            for chunk in response_stream.iter_content(chunk_size=8192):
                f.write(chunk)
