-- Community Forum Migration for BroadcastBeat
-- Tables: forum_categories, forum_threads, forum_replies

-- ============================================================
-- 1. TYPES
-- ============================================================
DROP TYPE IF EXISTS public.forum_thread_status CASCADE;
CREATE TYPE public.forum_thread_status AS ENUM ('open', 'closed', 'pinned');

-- ============================================================
-- 2. TABLES
-- ============================================================

CREATE TABLE IF NOT EXISTS public.forum_categories (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    slug TEXT NOT NULL UNIQUE,
    name TEXT NOT NULL,
    description TEXT,
    icon TEXT DEFAULT '💬',
    display_order INTEGER DEFAULT 0,
    thread_count INTEGER DEFAULT 0,
    post_count INTEGER DEFAULT 0,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS public.forum_threads (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    category_id UUID NOT NULL REFERENCES public.forum_categories(id) ON DELETE CASCADE,
    author_id UUID REFERENCES public.user_profiles(id) ON DELETE SET NULL,
    author_name TEXT NOT NULL DEFAULT 'Anonymous',
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    status public.forum_thread_status DEFAULT 'open'::public.forum_thread_status,
    reply_count INTEGER DEFAULT 0,
    view_count INTEGER DEFAULT 0,
    is_ai_seeded BOOLEAN DEFAULT false,
    last_reply_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS public.forum_replies (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    thread_id UUID NOT NULL REFERENCES public.forum_threads(id) ON DELETE CASCADE,
    author_id UUID REFERENCES public.user_profiles(id) ON DELETE SET NULL,
    author_name TEXT NOT NULL DEFAULT 'Anonymous',
    body TEXT NOT NULL,
    is_ai_response BOOLEAN DEFAULT false,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

-- ============================================================
-- 3. INDEXES
-- ============================================================
CREATE INDEX IF NOT EXISTS idx_forum_threads_category_id ON public.forum_threads(category_id);
CREATE INDEX IF NOT EXISTS idx_forum_threads_created_at ON public.forum_threads(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_forum_threads_last_reply_at ON public.forum_threads(last_reply_at DESC);
CREATE INDEX IF NOT EXISTS idx_forum_replies_thread_id ON public.forum_replies(thread_id);
CREATE INDEX IF NOT EXISTS idx_forum_categories_slug ON public.forum_categories(slug);

-- ============================================================
-- 4. FUNCTIONS
-- ============================================================

-- Update thread reply count and last_reply_at when a reply is added/deleted
CREATE OR REPLACE FUNCTION public.update_thread_reply_stats()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
    IF TG_OP = 'INSERT' THEN
        UPDATE public.forum_threads
        SET reply_count = reply_count + 1,
            last_reply_at = NEW.created_at,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = NEW.thread_id;

        UPDATE public.forum_categories
        SET post_count = post_count + 1,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = (SELECT category_id FROM public.forum_threads WHERE id = NEW.thread_id LIMIT 1);
    ELSIF TG_OP = 'DELETE' THEN
        UPDATE public.forum_threads
        SET reply_count = GREATEST(reply_count - 1, 0),
            updated_at = CURRENT_TIMESTAMP
        WHERE id = OLD.thread_id;

        UPDATE public.forum_categories
        SET post_count = GREATEST(post_count - 1, 0),
            updated_at = CURRENT_TIMESTAMP
        WHERE id = (SELECT category_id FROM public.forum_threads WHERE id = OLD.thread_id LIMIT 1);
    END IF;
    RETURN COALESCE(NEW, OLD);
END;
$$;

-- Update category thread count when a thread is added/deleted
CREATE OR REPLACE FUNCTION public.update_category_thread_count()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
    IF TG_OP = 'INSERT' THEN
        UPDATE public.forum_categories
        SET thread_count = thread_count + 1,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = NEW.category_id;
    ELSIF TG_OP = 'DELETE' THEN
        UPDATE public.forum_categories
        SET thread_count = GREATEST(thread_count - 1, 0),
            updated_at = CURRENT_TIMESTAMP
        WHERE id = OLD.category_id;
    END IF;
    RETURN COALESCE(NEW, OLD);
END;
$$;

-- ============================================================
-- 5. ENABLE RLS
-- ============================================================
ALTER TABLE public.forum_categories ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.forum_threads ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.forum_replies ENABLE ROW LEVEL SECURITY;

-- ============================================================
-- 6. RLS POLICIES
-- ============================================================

-- Forum categories: public read, no direct write (managed via API)
DROP POLICY IF EXISTS "public_read_forum_categories" ON public.forum_categories;
CREATE POLICY "public_read_forum_categories"
ON public.forum_categories FOR SELECT TO public USING (true);

-- Forum threads: public read, authenticated users can create
DROP POLICY IF EXISTS "public_read_forum_threads" ON public.forum_threads;
CREATE POLICY "public_read_forum_threads"
ON public.forum_threads FOR SELECT TO public USING (true);

DROP POLICY IF EXISTS "authenticated_create_forum_threads" ON public.forum_threads;
CREATE POLICY "authenticated_create_forum_threads"
ON public.forum_threads FOR INSERT TO authenticated
WITH CHECK (true);

DROP POLICY IF EXISTS "authors_update_own_forum_threads" ON public.forum_threads;
CREATE POLICY "authors_update_own_forum_threads"
ON public.forum_threads FOR UPDATE TO authenticated
USING (author_id = auth.uid())
WITH CHECK (author_id = auth.uid());

-- Forum replies: public read, authenticated users can create
DROP POLICY IF EXISTS "public_read_forum_replies" ON public.forum_replies;
CREATE POLICY "public_read_forum_replies"
ON public.forum_replies FOR SELECT TO public USING (true);

DROP POLICY IF EXISTS "authenticated_create_forum_replies" ON public.forum_replies;
CREATE POLICY "authenticated_create_forum_replies"
ON public.forum_replies FOR INSERT TO authenticated
WITH CHECK (true);

DROP POLICY IF EXISTS "authors_update_own_forum_replies" ON public.forum_replies;
CREATE POLICY "authors_update_own_forum_replies"
ON public.forum_replies FOR UPDATE TO authenticated
USING (author_id = auth.uid())
WITH CHECK (author_id = auth.uid());

-- Service role can do everything (for seeding and AI responses)
DROP POLICY IF EXISTS "service_role_manage_forum_categories" ON public.forum_categories;
CREATE POLICY "service_role_manage_forum_categories"
ON public.forum_categories FOR ALL TO service_role USING (true) WITH CHECK (true);

DROP POLICY IF EXISTS "service_role_manage_forum_threads" ON public.forum_threads;
CREATE POLICY "service_role_manage_forum_threads"
ON public.forum_threads FOR ALL TO service_role USING (true) WITH CHECK (true);

DROP POLICY IF EXISTS "service_role_manage_forum_replies" ON public.forum_replies;
CREATE POLICY "service_role_manage_forum_replies"
ON public.forum_replies FOR ALL TO service_role USING (true) WITH CHECK (true);

-- ============================================================
-- 7. TRIGGERS
-- ============================================================
DROP TRIGGER IF EXISTS on_forum_reply_change ON public.forum_replies;
CREATE TRIGGER on_forum_reply_change
AFTER INSERT OR DELETE ON public.forum_replies
FOR EACH ROW EXECUTE FUNCTION public.update_thread_reply_stats();

DROP TRIGGER IF EXISTS on_forum_thread_change ON public.forum_threads;
CREATE TRIGGER on_forum_thread_change
AFTER INSERT OR DELETE ON public.forum_threads
FOR EACH ROW EXECUTE FUNCTION public.update_category_thread_count();

-- ============================================================
-- 8. SEED CATEGORIES
-- ============================================================
DO $$
BEGIN
    INSERT INTO public.forum_categories (id, slug, name, description, icon, display_order) VALUES
        (gen_random_uuid(), 'live-production', 'Live Production', 'Discussions on live broadcast workflows, switching, graphics, and production techniques.', '🎬', 1),
        (gen_random_uuid(), 'ip-cloud', 'IP & Cloud', 'IP-based production, cloud workflows, remote production, and SMPTE ST 2110.', '☁️', 2),
        (gen_random_uuid(), 'audio', 'Audio', 'Broadcast audio engineering, mixing consoles, codecs, and monitoring.', '🎙️', 3),
        (gen_random_uuid(), 'cameras', 'Cameras & Lenses', 'Broadcast cameras, cinema cameras, lenses, and acquisition formats.', '📷', 4),
        (gen_random_uuid(), 'storage-mam', 'Storage & MAM', 'Media asset management, storage systems, archiving, and nearline/offline workflows.', '💾', 5),
        (gen_random_uuid(), 'streaming', 'Streaming & OTT', 'Video streaming, OTT platforms, encoding, CDN, and delivery.', '📡', 6),
        (gen_random_uuid(), 'ai-automation', 'AI & Automation', 'AI in broadcast, automated production, machine learning, and workflow automation.', '🤖', 7),
        (gen_random_uuid(), 'post-production', 'Post Production', 'Editing, color grading, VFX, finishing, and delivery workflows.', '🎞️', 8),
        (gen_random_uuid(), 'nab-ibc', 'NAB & IBC', 'Trade show coverage, product announcements, and industry events.', '🏛️', 9),
        (gen_random_uuid(), 'career-jobs', 'Career & Jobs', 'Career advice, job postings, freelance tips, and professional development.', '💼', 10),
        (gen_random_uuid(), 'gear-reviews', 'Gear Reviews', 'User reviews, comparisons, and hands-on experiences with broadcast equipment.', '⭐', 11),
        (gen_random_uuid(), 'general', 'General Discussion', 'Off-topic conversations, introductions, and anything broadcast-related.', '💬', 12)
    ON CONFLICT (slug) DO NOTHING;
END $$;

-- ============================================================
-- 9. SEED EDITORIAL STARTER THREADS
-- ============================================================
DO $$
DECLARE
    cat_live UUID;
    cat_ip UUID;
    cat_audio UUID;
    cat_cameras UUID;
    cat_storage UUID;
    cat_streaming UUID;
    cat_ai UUID;
    cat_post UUID;
    cat_nab UUID;
    cat_career UUID;
    cat_reviews UUID;
    cat_general UUID;
    t_id UUID;
BEGIN
    SELECT id INTO cat_live FROM public.forum_categories WHERE slug = 'live-production' LIMIT 1;
    SELECT id INTO cat_ip FROM public.forum_categories WHERE slug = 'ip-cloud' LIMIT 1;
    SELECT id INTO cat_audio FROM public.forum_categories WHERE slug = 'audio' LIMIT 1;
    SELECT id INTO cat_cameras FROM public.forum_categories WHERE slug = 'cameras' LIMIT 1;
    SELECT id INTO cat_storage FROM public.forum_categories WHERE slug = 'storage-mam' LIMIT 1;
    SELECT id INTO cat_streaming FROM public.forum_categories WHERE slug = 'streaming' LIMIT 1;
    SELECT id INTO cat_ai FROM public.forum_categories WHERE slug = 'ai-automation' LIMIT 1;
    SELECT id INTO cat_post FROM public.forum_categories WHERE slug = 'post-production' LIMIT 1;
    SELECT id INTO cat_nab FROM public.forum_categories WHERE slug = 'nab-ibc' LIMIT 1;
    SELECT id INTO cat_career FROM public.forum_categories WHERE slug = 'career-jobs' LIMIT 1;
    SELECT id INTO cat_reviews FROM public.forum_categories WHERE slug = 'gear-reviews' LIMIT 1;
    SELECT id INTO cat_general FROM public.forum_categories WHERE slug = 'general' LIMIT 1;

    -- Live Production threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_live, 'TechDirectorMike', 'Best practices for multi-camera live switching in 2025?',
        'We are upgrading our live production setup for a major sports network. Currently running an older Ross Carbonite but considering moving to a newer platform. What are people using for large-scale live events these days? Particularly interested in how others handle instant replay integration and graphics playout from a single switcher workflow.',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'BroadcastVet_Sarah', 'We moved to the Grass Valley Korona last year for our NFL coverage. The integration with Viz graphics is seamless and the replay workflow with EVS is much cleaner than what we had before. The learning curve for operators was about two weeks.', false),
           (t_id, 'LiveProdGuru', 'Ross Carbonite Black is still solid if you are already in that ecosystem. The latest firmware added a lot of IP features. But if you are doing a full refresh, the Sony XVS-G1 is worth a serious look for the price point.', false),
           (t_id, 'SwitcherTech_Dan', 'Do not overlook the Blackmagic ATEM Constellation for mid-tier productions. We use it for college sports and it handles 4K HDR without breaking the bank. The software control panel is surprisingly capable.', false)
    ON CONFLICT DO NOTHING;

    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_live, 'RemoteProdEngineer', 'REMI vs full remote production — where is the industry heading?',
        'Been having a lot of internal debates about whether to invest in a full REMI (Remote Integration Model) setup or go all-in on cloud-based remote production. The latency improvements in the last two years have been significant but we still have clients who are nervous about cloud reliability for live events. What is your experience?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'CloudBroadcaster_J', 'We have been doing full cloud production for tier-2 sports for 18 months. The key is redundant connectivity — we run dual bonded cellular as backup to fiber. Had zero on-air failures since we added that layer.', false),
           (t_id, 'TechDirectorMike', 'REMI still makes sense when you need the tactile control of physical hardware at a central hub. Full cloud is great for lower-complexity shows but for a 12-camera live drama with complex audio, I still want engineers in a truck.', false)
    ON CONFLICT DO NOTHING;

    -- IP & Cloud threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_ip, 'IPEngineer_Tom', 'ST 2110 migration — lessons learned from our facility upgrade',
        'Just completed a full ST 2110 migration at our broadcast center after 18 months of planning and 6 months of execution. Happy to share what went wrong and what went right. The biggest surprise was how much time we spent on PTP synchronization issues. Anyone else find that the timing infrastructure was the hardest part?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'NetworkBroadcast_K', 'PTP was our nightmare too. We ended up deploying a dedicated grandmaster clock per building and that solved 90% of our timing issues. The Meinberg LANTIME series has been rock solid for us.', false),
           (t_id, 'ST2110_Specialist', 'What switch fabric did you end up with? We are evaluating Arista vs Cisco Nexus for our migration and the multicast configuration differences are significant.', false),
           (t_id, 'IPEngineer_Tom', 'We went Arista 7050CX3. The IGMP snooping configuration was well documented and their broadcast support team actually knows what ST 2110 is, which was refreshing.', false)
    ON CONFLICT DO NOTHING;

    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_ip, 'CloudArchitect_V', 'AWS vs Azure vs GCP for broadcast cloud production — real-world comparison',
        'We have been running workloads on all three major clouds for different clients over the past two years. Each has distinct strengths for broadcast. AWS Elemental is mature but expensive. Azure has better enterprise integration. GCP has interesting live streaming primitives. What is everyone else seeing?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'BroadcastCloud_R', 'AWS Elemental MediaLive is still the most feature-complete for live broadcast. The SCTE-35 handling alone makes it worth the premium for ad-supported content.', false),
           (t_id, 'MultiCloudEng', 'We run a hybrid — AWS for live encoding, Azure for MAM and archive because of the Active Directory integration, and GCP for ML-based content analysis. No single cloud does everything best.', false)
    ON CONFLICT DO NOTHING;

    -- Audio threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_audio, 'AudioEngineer_Lisa', 'Dante vs AES67 vs MADI — which audio networking standard are you standardizing on?',
        'Our facility is due for an audio infrastructure refresh and we are trying to decide between going all-in on Dante, adopting AES67 for interoperability, or sticking with MADI for its simplicity and reliability. We do a mix of live production and post. What are the real-world trade-offs people are experiencing?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'SoundDesigner_P', 'Dante for anything that needs to be flexible and reconfigurable quickly. AES67 when you need to interop with non-Audinate gear. MADI only if you have a specific legacy reason. That is the hierarchy I use.', false),
           (t_id, 'LiveAudioMixer', 'We standardized on Dante three years ago and have not looked back. The Dante Controller software makes routing changes that used to take an hour take five minutes. The latency is predictable and the redundancy options are solid.', false),
           (t_id, 'AudioEngineer_Lisa', 'Good points. Our concern with Dante is vendor lock-in. Has anyone had issues with the licensing costs as you scale up device count?', false)
    ON CONFLICT DO NOTHING;

    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_audio, 'MixerTech_B', 'Loudness compliance headaches — EBU R128 vs ATSC A/85 in a global workflow',
        'We deliver content to both European and North American broadcasters and managing loudness compliance across both standards is a constant pain. We are using iZotope RX for post but for live we are still doing it manually. Anyone found a good automated solution that handles both standards simultaneously?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'LoudnessGuru', 'Orban Optimod-PC is what we use for live. It handles both R128 and A/85 profiles and you can switch between them on the fly. The automatic gain riding is transparent enough that most clients cannot tell it is engaged.', false),
           (t_id, 'PostAudioEng', 'For post we use Nugen Audio VisLM for monitoring and MasterCheck for final compliance verification. The dual-standard metering in a single view saves a lot of time.', false)
    ON CONFLICT DO NOTHING;

    -- Cameras threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_cameras, 'CameraOp_James', 'Sony HDC-5500 vs Grass Valley LDX 150 for studio sports — which would you choose?',
        'We are spec-ing out a new studio for a regional sports network. The two cameras on our shortlist are the Sony HDC-5500 and the Grass Valley LDX 150. Both are excellent but the price difference is significant. For a studio environment doing primarily basketball and hockey, is the GV worth the premium?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'StudioCamTech', 'The LDX 150 has better highlight handling for ice hockey — the specular reflections off the ice are brutal and the GV sensor handles them more gracefully. For basketball the Sony is fine. Depends on your primary sport.', false),
           (t_id, 'BroadcastDP_A', 'Do not forget to factor in the CCU ecosystem. If you are already Sony house, the HDC-5500 integrates better with your existing infrastructure. Mixing CCU systems is a headache you do not want.', false),
           (t_id, 'CameraOp_James', 'We are currently a mixed shop — some Sony, some Ikegami. Leaning toward standardizing on one platform with this purchase. The Sony ecosystem argument is compelling.', false)
    ON CONFLICT DO NOTHING;

    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_cameras, 'FilmToBroadcast_C', 'Cinema cameras in broadcast — where does it make sense?',
        'More and more broadcast productions are using cinema cameras like the ARRI Alexa 35 or RED Monstro for certain applications. We are considering them for our documentary unit. What are the practical challenges of integrating cinema cameras into a broadcast workflow — particularly around color management and metadata?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'ColoristPro_N', 'The color management pipeline is the biggest challenge. You need a solid LUT strategy and everyone in the chain needs to understand it. ACES is theoretically the answer but in practice most broadcast facilities are not set up for it end to end.', false),
           (t_id, 'DocCameraOp', 'We use ARRI Amiras for our doc unit. The key is having a dedicated DIT on set who manages the color pipeline from capture to delivery. Without that discipline the footage becomes a nightmare in post.', false)
    ON CONFLICT DO NOTHING;

    -- Storage & MAM threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_storage, 'MAMAdmin_Greg', 'Evaluating MAM systems for a mid-size broadcaster — Iconik vs Cantemo vs Dalet',
        'We are a regional broadcaster with about 50TB of active content and 500TB in archive. Currently using a homegrown system that is falling apart. Evaluating Iconik, Cantemo Portal, and Dalet Galaxy. Anyone have real-world experience with these at similar scale? Particularly interested in the AI metadata features.',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'MediaOps_H', 'Iconik is excellent for cloud-native workflows and the API is well documented. If you have developers who can build integrations it is very flexible. The AI tagging via Google Video Intelligence is genuinely useful.', false),
           (t_id, 'ArchivistPro', 'Dalet Galaxy is the most feature-complete but also the most complex to implement and maintain. For your scale I would look seriously at Iconik first — it is much faster to get running and the ongoing cost is more predictable.', false),
           (t_id, 'MAMAdmin_Greg', 'Thanks for the Iconik recommendation. We did a demo last week and the cloud-first architecture appeals to us. Did you find the on-premise proxy generation adequate or did you need to supplement it?', false)
    ON CONFLICT DO NOTHING;

    -- Streaming threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_streaming, 'StreamingEng_F', 'HEVC vs AV1 for OTT delivery in 2025 — is AV1 ready for prime time?',
        'We are planning a codec refresh for our OTT platform. AV1 offers significant bitrate savings over HEVC but the encoding complexity and device support have been concerns. With the latest hardware encoder support from Intel and NVIDIA, has the calculus changed? What are people actually deploying?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'OTTPlatformEng', 'AV1 is ready for VOD. For live it is still challenging because of encoding latency even with hardware acceleration. We use AV1 for our VOD catalog and HEVC for live. The bitrate savings on VOD are 30-40% at equivalent quality.', false),
           (t_id, 'CDNArchitect', 'Device support is the real constraint. Smart TVs from 2020 and earlier often do not support AV1 hardware decode. If your audience skews older devices, HEVC is still the safer choice for live.', false),
           (t_id, 'StreamingEng_F', 'Good point on device support. Our analytics show 15% of viewers on devices that do not support AV1. We are thinking about a dual-encode strategy but the cost implications are significant.', false)
    ON CONFLICT DO NOTHING;

    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_streaming, 'LatencyObsessed', 'Sub-second latency for live sports streaming — what is actually achievable?',
        'Our sports rights holders are demanding sub-second latency to match linear broadcast. We are currently at 4-6 seconds with HLS. We have been evaluating WebRTC and HESP. Has anyone deployed either at scale for sports? What were the trade-offs in quality and reliability?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'WebRTCExpert', 'WebRTC can get you under 500ms but scaling beyond 10,000 concurrent viewers requires a sophisticated SFU architecture. Cloudflare Stream and Mux both offer managed WebRTC that takes the infrastructure burden off you.', false),
           (t_id, 'HESPEvangelst', 'HESP (High Efficiency Streaming Protocol) is worth evaluating. It achieves sub-second latency with better quality than WebRTC at scale. THEOplayer has the most mature implementation.', false)
    ON CONFLICT DO NOTHING;

    -- AI & Automation threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_ai, 'AIBroadcast_W', 'AI-powered automated camera direction — hype or reality?',
        'Vendors are pitching AI camera direction as a way to reduce crew costs for tier-2 sports and corporate events. We have piloted two systems and the results were mixed. The AI is good at tracking action but struggles with editorial judgment — knowing when to cut away, when to stay wide, how to build tension. What has your experience been?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'AutoProdTech', 'We use Vizrt Viz Mosart for automated studio production and it is genuinely good for structured formats like news. For sports the editorial judgment problem you describe is real — it is great at following the ball but terrible at storytelling.', false),
           (t_id, 'SportsTVDirector', 'The best implementations I have seen use AI as a tool for the director, not a replacement. AI handles the routine coverage — wide shots, replays — while the human director focuses on the key moments. That hybrid approach works well.', false),
           (t_id, 'AIBroadcast_W', 'That hybrid model is where we are landing too. The ROI case is harder to make when you still need a director, but the AI does reduce the number of camera operators needed significantly.', false)
    ON CONFLICT DO NOTHING;

    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_ai, 'MLEngineer_Broadcast', 'Using LLMs for automated closed captioning and transcript generation — accuracy benchmarks',
        'We have been benchmarking several AI captioning solutions against our manual captioning accuracy standards. OpenAI Whisper, AWS Transcribe, and Google Speech-to-Text all perform differently on broadcast content — especially with sports commentary, technical jargon, and accented speech. Happy to share our benchmark data if there is interest.',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'AccessibilityEng', 'Please share the benchmark data — this is exactly what we need. We are under regulatory pressure to improve our captioning accuracy and the vendor claims are all over the place.', false),
           (t_id, 'CaptioningPro', 'Whisper large-v3 is the best open-source option but it is not real-time without significant GPU investment. For live we use AWS Transcribe with a custom vocabulary for sports terms and it gets us to about 96% accuracy on clear speech.', false)
    ON CONFLICT DO NOTHING;

    -- Post Production threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_post, 'EditorPro_M', 'Avid vs Premiere vs Resolve for broadcast post — 2025 state of the market',
        'The NLE landscape has shifted significantly. Avid is still dominant in high-end broadcast but DaVinci Resolve has made serious inroads, especially for facilities that want integrated color and audio. Premiere is everywhere but the stability issues have driven some shops away. Where is your facility landing?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'PostFacilityMgr', 'We moved from Avid to Resolve for our documentary and long-form work two years ago. The integrated color pipeline is a genuine productivity gain. We kept Avid for our news operation because the shared storage integration is still better.', false),
           (t_id, 'NewsEditor_T', 'Avid is not going anywhere in news. The iNEWS integration and the shared bin workflow for breaking news is irreplaceable. Resolve is great for long-form but it is not built for the chaos of a live news operation.', false),
           (t_id, 'IndiePostPro', 'Resolve is eating Premiere''s lunch at the indie and mid-tier level. The free version is genuinely professional-grade now and the Studio version is a fraction of the cost of Avid. For anything that is not news or high-end drama, it is hard to justify the alternatives.', false)
    ON CONFLICT DO NOTHING;

    -- NAB & IBC threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_nab, 'NABRegular_E', 'NAB 2025 — what are you most excited to see on the show floor?',
        'NAB is coming up and I am trying to plan my time efficiently. The show has gotten so large that you really need a strategy. I am particularly interested in IP infrastructure, AI production tools, and the latest camera systems. What is on your must-see list this year?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'ShowFloorVet', 'The Central Hall IP pavilion has gotten much better organized. I always start there to get a sense of where the infrastructure market is heading. The Sony and Grass Valley booths are worth the time for camera announcements.', false),
           (t_id, 'StartupWatcher', 'The startup pavilion in the South Hall has had some genuinely interesting companies the last few years. That is where I found the AI captioning vendor we ended up deploying. Worth a few hours if you can spare them.', false)
    ON CONFLICT DO NOTHING;

    -- Career threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_career, 'NewToBC_Q', 'Breaking into broadcast engineering — advice for someone coming from IT?',
        'I have a strong IT background (networking, Linux, virtualization) and I am trying to transition into broadcast engineering. The IP transition in broadcast seems like a natural fit for my skills. What certifications or experience would make me most attractive to broadcast employers? Is the SBE certification worth pursuing?',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'BroadcastHiringMgr', 'Your IT background is genuinely valuable right now. SBE certification shows commitment to the field and the CBTE (Certified Broadcast Television Engineer) is the most recognized. But honestly, hands-on experience with broadcast-specific gear matters more than certifications.', false),
           (t_id, 'CareerBroadcaster', 'Look for opportunities at local stations or production companies that are doing IP migrations. They need people who understand networking and are willing to learn the broadcast-specific layer on top. That combination is hard to find.', false),
           (t_id, 'NewToBC_Q', 'Thank you both. I have been studying SMPTE ST 2110 documentation on my own. Is there a good lab environment I can set up at home to get hands-on experience without access to professional gear?', false)
    ON CONFLICT DO NOTHING;

    -- Gear Reviews threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_reviews, 'GearReviewer_Z', 'Six months with the Blackmagic ATEM Constellation 8K — honest review',
        'We purchased two ATEM Constellation 8K units six months ago for our live event production company. Here is my honest assessment after real-world use: the value proposition is extraordinary, the software control panel is more capable than I expected, but there are some reliability quirks that Blackmagic needs to address. Full review in the thread.',
        true, 'open') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'LiveEventPro', 'What reliability quirks are you seeing? We are considering the same unit for a similar application and I want to know what to watch out for.', false),
           (t_id, 'GearReviewer_Z', 'The main issue is occasional macro execution failures under heavy load — the switcher gets busy and macros do not fire reliably. Blackmagic acknowledged it and said a firmware fix is coming. Also the HDMI inputs are more fragile than the SDI inputs in my experience.', false),
           (t_id, 'BMDUser_X', 'We had the same macro issue. The workaround is to add a small delay between macro steps. Not ideal but it works until the firmware fix arrives. Overall still the best value in that class.', false)
    ON CONFLICT DO NOTHING;

    -- General threads
    t_id := gen_random_uuid();
    INSERT INTO public.forum_threads (id, category_id, author_name, title, body, is_ai_seeded, status)
    VALUES (t_id, cat_general, 'BroadcastBeat_Team', 'Welcome to the BroadcastBeat Community Forum!',
        'Welcome to the BroadcastBeat Community Forum — the place for broadcast engineering professionals to connect, share knowledge, and discuss the technology shaping our industry. Whether you are a seasoned chief engineer or just starting your career, this is your community. Introduce yourself below and tell us what you work on!',
        true, 'pinned') ON CONFLICT (id) DO NOTHING;
    INSERT INTO public.forum_replies (thread_id, author_name, body, is_ai_response)
    VALUES (t_id, 'ChiefEngineer_NY', 'Great to see BroadcastBeat launching a forum. I am a chief engineer at a major network affiliate in New York. Looking forward to connecting with peers here.', false),
           (t_id, 'FreelanceBroadcast', 'Freelance broadcast engineer based in LA. I work across live events, sports, and some scripted production. Always looking to learn from others in the field.', false)
    ON CONFLICT DO NOTHING;

EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'Forum seed data error: %', SQLERRM;
END $$;
