<?php

namespace App\Models\Synapse;

use App\Models\Communication\Recording;
use App\Trait\BelongsToSolicitor;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SynapseTranscript extends Model
{
    use BelongsToSolicitor;

    protected $fillable = [
        'recording_id',
        'solicitor_id',
        'provider',
        'provider_transcript_id',
        'raw_transcript',
        'formatted_transcript',
        'ai_summary',
        'sentiment_data',
        'status',
        'error',
    ];

    protected $casts = [
        'sentiment_data' => 'array',
    ];

    /**
     * Sentiment breakdown as percentages, e.g. ['positive' => 60, 'negative' => 20, 'neutral' => 20].
     */
    public function getSentimentBreakdownAttribute(): array
    {
        $data = $this->sentiment_data;

        if (empty($data)) {
            return [];
        }

        $total = count($data);
        $counts = ['POSITIVE' => 0, 'NEGATIVE' => 0, 'NEUTRAL' => 0];

        foreach ($data as $item) {
            $key = strtoupper($item['sentiment'] ?? 'NEUTRAL');
            $counts[$key] = ($counts[$key] ?? 0) + 1;
        }

        return [
            'positive' => $total > 0 ? (int) round($counts['POSITIVE'] / $total * 100) : 0,
            'negative' => $total > 0 ? (int) round($counts['NEGATIVE'] / $total * 100) : 0,
            'neutral'  => $total > 0 ? (int) round($counts['NEUTRAL']  / $total * 100) : 0,
        ];
    }

    public function recording(): BelongsTo
    {
        return $this->belongsTo(Recording::class);
    }
}
