"""Log ingestion service."""

import hashlib
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession

from src.models.scenario_log import ScenarioLog
from src.models.scenario import Scenario
from src.repositories.scenario import scenario_repository
from src.services.pii_detector import pii_detector
from src.profiler import count_tokens, calculate_sqs_blocks


class IngestService:
    """Service for processing and ingesting logs."""

    async def ingest_log(
        self,
        db: AsyncSession,
        scenario: Scenario,
        message: str,
        source: str = "unknown",
    ) -> ScenarioLog:
        """Process and save a log entry."""

        # Calculate message hash for deduplication
        message_hash = hashlib.sha256(message.encode()).hexdigest()

        # Truncate message for preview (privacy)
        message_preview = message[:500] if len(message) > 500 else message

        # Detect PII
        has_pii = pii_detector.detect_simple(message)

        # Calculate metrics
        token_count = count_tokens(message)
        payload_size = len(message.encode("utf-8"))
        sqs_blocks = calculate_sqs_blocks(message)

        # Create log entry
        log_entry = ScenarioLog(
            scenario_id=scenario.id,
            received_at=datetime.utcnow(),
            message_hash=message_hash,
            message_preview=message_preview,
            source=source,
            size_bytes=payload_size,
            has_pii=has_pii,
            token_count=token_count,
            sqs_blocks=sqs_blocks,
        )

        db.add(log_entry)

        # Update scenario metrics
        await scenario_repository.increment_total_requests(db, scenario.id)

        await db.commit()
        await db.refresh(log_entry)

        return log_entry


# Singleton instance
ingest_service = IngestService()
