<?php

namespace App\Services;

use App\Exceptions\DuplicateCcliSongException;
use App\Models\ApiRequestLog;
use App\Models\Label;
use App\Models\Setting;
use App\Models\Song;
use App\Models\SongArrangement;
use App\Models\SongArrangementLabel;
use App\Models\SongSection;
use App\Services\DTO\ParsedCcliSection;
use App\Services\DTO\ParsedCcliSong;
use App\Support\CcliLabels;
use Illuminate\Support\Facades\DB;
use RuntimeException;

final class CcliImportService
{
    /**
     * Number of lyric lines grouped into a single projection slide.
     */
    private const LINES_PER_SLIDE = 2;

    private const LABEL_KIND_COLORS = [
        'Verse' => '#3B82F6',
        'Chorus' => '#10B981',
        'Bridge' => '#F59E0B',
        'Pre-Chorus' => '#8B5CF6',
        'Tag' => '#EC4899',
        'Ending' => '#EF4444',
        'Intro' => '#14B8A6',
        'Interlude' => '#6366F1',
        'Outro' => '#F97316',
        'Misc' => '#64748B',
    ];

    public function __construct(
        private readonly CcliPasteParser $parser,
        private readonly SongPrefixPostfixService $songPrefixPostfixService,
    ) {}

    /** @return array{song: Song, status: 'created'|'restored', warnings: string[]} */
    public function import(string $rawText, ?string $sourceUrl = null): array
    {
        $startedAt = microtime(true);
        $parsed = $this->parser->parse($rawText);

        if ($parsed->ccliId === null || trim($parsed->ccliId) === '') {
            throw new RuntimeException('Keine CCLI-Nummer gefunden — bitte vollständige SongSelect-Liedseite einfügen.');
        }

        $song = Song::withTrashed()->where('ccli_id', $parsed->ccliId)->first();
        $status = 'created';

        if ($song !== null && ! $song->trashed() && $this->songHasContent($song)) {
            throw new DuplicateCcliSongException($song->id);
        }

        if ($song !== null) {
            $status = 'restored';
        }

        return DB::transaction(function () use ($parsed, $sourceUrl, $song, $status, $startedAt): array {
            if ($song !== null && $song->trashed()) {
                $song->restore();
            }

            $song = $this->upsertSong($parsed, $sourceUrl, $song);
            $warnings = [];

            $translationLanguage = Setting::get('default_translation_language', 'DE');
            if ($translationLanguage === null || trim($translationLanguage) === '') {
                $warnings[] = 'Keine Standard-Übersetzungssprache gesetzt, DE wird verwendet.';
            }

            $sectionIds = [];
            $hasTranslation = false;

            foreach ($parsed->sections as $order => $parsedSection) {
                $label = $this->resolveLabel($parsedSection);
                $section = SongSection::firstOrCreate(
                    ['song_id' => $song->id, 'label_id' => $label->id],
                    ['order' => $order + 1],
                );
                $section->update(['order' => $order + 1]);
                $sectionIds[] = $section->id;

                $section->slides()->delete();

                // Group lines into pairs: each slide carries up to two lines.
                $lineChunks = array_chunk($parsedSection->lines, self::LINES_PER_SLIDE);
                $translatedChunks = $parsedSection->linesTranslated !== null
                    ? array_chunk($parsedSection->linesTranslated, self::LINES_PER_SLIDE)
                    : [];

                foreach ($lineChunks as $slideOrder => $chunk) {
                    $translatedChunk = $translatedChunks[$slideOrder] ?? null;
                    $translatedLine = $translatedChunk !== null ? implode("\n", $translatedChunk) : null;
                    $hasTranslation = $hasTranslation || ($translatedLine !== null && trim($translatedLine) !== '');

                    $section->slides()->create([
                        'order' => $slideOrder + 1,
                        'text_content' => implode("\n", $chunk),
                        'text_content_translated' => $translatedLine,
                    ]);
                }
            }

            $song->update([
                'has_translation' => $hasTranslation,
                'imported_from_ccli_at' => now(),
                'ccli_source_url' => $sourceUrl ?? $parsed->sourceUrl,
            ]);

            $arrangement = SongArrangement::updateOrCreate(
                ['song_id' => $song->id, 'name' => 'normal'],
                ['is_default' => true],
            );

            SongArrangementLabel::where('song_arrangement_id', $arrangement->id)->delete();

            foreach ($sectionIds as $order => $sectionId) {
                SongArrangementLabel::create([
                    'song_arrangement_id' => $arrangement->id,
                    'song_section_id' => $sectionId,
                    'order' => $order + 1,
                ]);
            }

            $this->songPrefixPostfixService->ensure($song);

            $song = $song->fresh(['arrangements.arrangementSections.section.slides', 'arrangements.arrangementSections.section.label']);

            ApiRequestLog::create([
                'method' => 'import',
                'endpoint' => 'paste',
                'status' => 'success',
                'request_context' => ['ccli_id' => $parsed->ccliId, 'mode' => $status],
                'response_summary' => "Song {$status}: {$song->title}",
                'response_body' => null,
                'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000),
            ]);

            return ['song' => $song, 'status' => $status, 'warnings' => $warnings];
        });
    }

    private function upsertSong(ParsedCcliSong $parsed, ?string $sourceUrl, ?Song $song): Song
    {
        $songData = [
            'title' => $parsed->title,
            'author' => $parsed->author,
            'copyright_text' => $parsed->copyrightText,
            'copyright_year' => $parsed->year,
            'publisher' => $parsed->copyrightText,
            'ccli_source_url' => $sourceUrl ?? $parsed->sourceUrl,
        ];

        if ($song !== null) {
            $song->update($songData);

            return $song;
        }

        return Song::create(array_merge($songData, ['ccli_id' => $parsed->ccliId]));
    }

    private function songHasContent(Song $song): bool
    {
        return $song->sections()
            ->where(fn ($q) => $q->where('locked', false)->orWhereNull('locked'))
            ->whereHas('slides')
            ->exists();
    }

    private function resolveLabel(ParsedCcliSection $section): Label
    {
        $canonicalKind = CcliLabels::normalizeLabelName($section->kind);
        $canonicalLabelName = CcliLabels::normalizeLabelName(
            $section->kind.($section->number ? ' '.$section->number : ''),
        );

        return Label::firstOrCreate(
            ['name' => $canonicalLabelName],
            ['color' => $this->labelColor($canonicalKind), 'last_imported_at' => now()],
        );
    }

    private function labelColor(string $canonicalKind): string
    {
        if (array_key_exists($canonicalKind, self::LABEL_KIND_COLORS)) {
            return self::LABEL_KIND_COLORS[$canonicalKind];
        }

        $colors = array_values(self::LABEL_KIND_COLORS);

        return $colors[crc32($canonicalKind) % count($colors)];
    }
}
