<?php

namespace Database\Seeders;

use App\Models\Course;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

/**
 * Imports the real Money Wise Academy courses (LearnDash) into the build:
 * chapters, topic lessons, Wistia videos, lesson body text and downloadable
 * materials. Course-level title/description/cover/price are left intact.
 *
 * Content (titles, body, material links) is read from the extracted
 * storage/app/academy-import/import2.json; the 7 downloadable files were
 * re-hosted under public/academy/. Demo LearnDash courses are excluded.
 */
class AcademyImportSeeder extends Seeder
{
    /** academy item id => Wistia media id (null = no video). */
    private const WISTIA = [
        25 => '3zmcrdiiac', 27 => '60fvk8p609', 29 => 't6fo63fz0r',
        31 => 'pzdvfsl1r9', 33 => 'nkq44ylc9x',
        36 => '7d1yi9fnbx', 38 => 'j539jea823',
        40 => 'cwbup3c00v', 42 => 'mkvwo9g6yc', 44 => '51pary3deh', 47 => 'q7e82mupot', 49 => 'dg6sruigl4',
        52 => null, 54 => null,
        2000 => '7niydmt3z6', 1996 => 'jn87df4mzr', 2040 => '1acbskbo3g', 1998 => '4o2murvd8h', 1994 => 'id09djhz6t',
    ];

    /** Wistia media id => runtime in minutes (from the Wistia media metadata). */
    private const DURATION = [
        '3zmcrdiiac' => 4, '60fvk8p609' => 4, 't6fo63fz0r' => 5, 'pzdvfsl1r9' => 4, 'nkq44ylc9x' => 4,
        '7d1yi9fnbx' => 10, 'j539jea823' => 3, 'cwbup3c00v' => 4, 'mkvwo9g6yc' => 2, '51pary3deh' => 8,
        'q7e82mupot' => 8, 'dg6sruigl4' => 8,
        '7niydmt3z6' => 59, 'jn87df4mzr' => 49, '1acbskbo3g' => 77, '4o2murvd8h' => 57, 'id09djhz6t' => 61,
    ];

    /** our course slug => [ [chapter academy id|null, fallback title, [topic academy ids...]], ... ]. */
    private const STRUCTURE = [
        'investable' => [
            [14, 'Principle of Seed & Fruit', [25, 27, 29]],
            [16, 'Discovering Your Why', [31, 33]],
            [18, 'Categorising Your Goals into Baskets', [36, 38]],
            [21, 'Investing Options Based on Your Goals', [40, 42, 44, 47, 49]],
            [23, 'Making It Practical', [52, 54]],
        ],
        'analyzing-financial-statements' => [[null, 'Course', [2000]]],
        'core-values-and-your-money' => [[null, 'Course', [1996]]],
        'crypto-basics' => [[null, 'Course', [2040]]],
        'planning-for-retirement' => [[null, 'Course', [1998]]],
        'retirement-benefits-options' => [[null, 'Course', [1994]]],
    ];

    private array $data = [];

    private function rewrite(string $url): string
    {
        if (preg_match('#academy\.moneywise\.co\.ke/wp-content/uploads/[^?]*/([^/?]+\.(?:pdf|xlsx?|docx?|pptx?|zip|csv))#i', $url, $m)) {
            return '/academy/'.$m[1];
        }
        return $url;
    }

    /** Build a [{label,url}] list from import2 links for the given academy ids. */
    private function materials(array $ids): array
    {
        $out = [];
        foreach ($ids as $id) {
            foreach ($this->data[$id]['links'] ?? [] as $l) {
                $url = $this->rewrite($l['url']);
                $label = $l['text'] !== '' ? $l['text'] : Str::headline(pathinfo(parse_url($url, PHP_URL_PATH) ?? $url, PATHINFO_FILENAME));
                $out[$url] = ['label' => $label, 'url' => $url];
            }
        }
        return array_values($out);
    }

    public function run(): void
    {
        $file = storage_path('app/academy-import/import2.json');
        $this->data = is_file($file) ? (json_decode(file_get_contents($file), true) ?: []) : [];

        foreach (self::STRUCTURE as $slug => $chapters) {
            $course = Course::where('slug', $slug)->first();
            if (! $course) {
                $this->command?->warn("AcademyImport: course '{$slug}' not found, skipped.");
                continue;
            }

            $course->modules()->delete();
            $first = true;

            foreach ($chapters as $mIndex => [$chapterId, $fallbackTitle, $topicIds]) {
                $module = $course->modules()->create([
                    'title' => $chapterId ? ($this->data[$chapterId]['title'] ?? $fallbackTitle) : $fallbackTitle,
                    'summary' => $chapterId ? ($this->data[$chapterId]['body'] ?: null) : null,
                    'sort' => $mIndex,
                ]);

                foreach ($topicIds as $lIndex => $tid) {
                    // Chapter-level downloads (e.g. the worksheet) attach to the chapter's first topic.
                    $matIds = $lIndex === 0 && $chapterId ? [$tid, $chapterId] : [$tid];

                    $title = $this->data[$tid]['title'] ?? $fallbackTitle;
                    $wid = self::WISTIA[$tid] ?? null;
                    $module->lessons()->create([
                        'title' => $title,
                        'slug' => Str::slug($title).'-'.$tid,
                        'body' => $this->data[$tid]['body'] ?: null,
                        'video_url' => $wid ? 'https://fast.wistia.net/embed/iframe/'.$wid : null,
                        'materials' => $this->materials($matIds) ?: null,
                        'duration_minutes' => $wid ? (self::DURATION[$wid] ?? 0) : 0,
                        // Only multi-lesson Investable offers a free preview; single-video
                        // paid masterclasses stay gated so the product isn't free to watch.
                        'is_free_preview' => $first && $slug === 'investable',
                        'sort' => $lIndex,
                    ]);
                    $first = false;
                }
            }

            $course->update(['is_published' => true]);
        }
    }
}
