"""Dados iniciais (idempotente). Conteúdo de exemplo: Blender Open Movies (Creative Commons) e streams de teste públicos."""
import uuid

IMG = ""
VID = ""
TV = "https://test-videos.co.uk/vids/"
BBB_IMG = "https://upload.wikimedia.org/wikipedia/commons/c/c5/Big_buck_bunny_poster_big.jpg"
BBB_BG = "https://peach.blender.org/wp-content/uploads/title_anouncement.jpg"
SINTEL_IMG = "https://upload.wikimedia.org/wikipedia/commons/8/8f/Sintel_poster.jpg"
SINTEL_BG = "https://durian.blender.org/wp-content/uploads/2010/06/05.8b_comp_000272.jpg"
TOS_IMG = "https://mango.blender.org/wp-content/uploads/2013/05/01_thom_celia_bridge.jpg"
ED_IMG = "https://orange.blender.org/wp-content/themes/orange/images/media/gallery/s1_proog.jpg"
U1 = "https://images.unsplash.com/photo-1627133805103-ce2d34ccdd37?w=900"
U2 = "https://images.unsplash.com/photo-1791010484572-14b22492cf5d?w=900"
U3 = "https://images.unsplash.com/photo-1693328394659-e0782c606d25?w=900"
U4 = "https://images.unsplash.com/photo-1751448555253-f39c06e29d82?w=900"
V_BBB = TV + "bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_1MB.mp4"
V_SINTEL = "https://download.blender.org/durian/trailer/sintel_trailer-480p.mp4"
V_SINTEL2 = TV + "sintel/mp4/h264/720/Sintel_720_10s_1MB.mp4"
V_TOS = "https://download.blender.org/demo/movies/ToS/tears_of_steel_720p.mov"
V_JELLY = TV + "jellyfish/mp4/h264/720/Jellyfish_720_10s_1MB.mp4"


VPN_DEFAULTS = {"protocol": "wireguard", "endpoint": "", "port": 51820, "public_key": "", "address_pool": "10.8.0.0/24",
                "dns": ["10.8.0.1"], "allowed_ips": "0.0.0.0/0, ::/0", "mtu": None, "persistent_keepalive": 25}


def _id():
    return str(uuid.uuid4())


async def seed_database(db, hash_password, now_iso, admin_user, admin_pw, demo_user, demo_pw):
    # Usuários (só cria se não existir — não sobrescreve senha alterada no painel)
    for username, pw, role, name in [(admin_user, admin_pw, "admin", "Administrador"), (demo_user, demo_pw, "user", "Usuário Teste")]:
        await db.users.update_one({"username": username}, {"$setOnInsert": {
            "id": _id(), "username": username, "name": name, "role": role, "active": True, "expires_at": None,
            "password_hash": hash_password(pw), "created_at": now_iso(),
            "must_change_password": role == "admin"}}, upsert=True)

    await db.config.update_one({"key": "app"}, {"$setOnInsert": {
        "key": "app", "app_name": "PLAY CHANNELS", "logo_url": "", "background_url": "",
        "primary_color": "#D91636", "welcome_message": "Seu entretenimento, em qualquer tela.",
        "maintenance": False,
        "vpn": {"enabled": True, "auto_reconnect": True, "kill_switch": True, "dns_leak_protection": True,
                "dns_servers": ["10.8.0.1"], "default_protocol": "wireguard"},
    }}, upsert=True)

    if await db.categories.count_documents({}) > 0:
        return

    cats = [{"id": _id(), "name": n, "order": i, "created_at": now_iso()} for i, n in
            enumerate(["Animação", "Ficção Científica", "Aventura", "Documentários"])]
    await db.categories.insert_many([dict(c) for c in cats])
    anim, scifi, adv, doc = [c["id"] for c in cats]

    def movie(title, file, img, synopsis, year, dur, cats_, featured=False):
        return {"id": _id(), "type": "movie", "title": title, "synopsis": synopsis, "year": year,
                "duration_min": dur, "rating": "L", "poster_url": img[0], "backdrop_url": img[1],
                "stream_url": file, "category_ids": cats_, "featured": featured, "active": True,
                "license": "Creative Commons / Blender Foundation", "created_at": now_iso()}

    movies = [
        movie("Big Buck Bunny", V_BBB, (BBB_IMG, BBB_BG),
              "Um coelho gigante e gentil decide dar uma lição em três roedores encrenqueiros (trecho de 10s).", 2008, 1, [anim, adv], True),
        movie("Sintel", V_SINTEL, (SINTEL_IMG, SINTEL_BG),
              "Uma jovem guerreira parte em uma jornada perigosa para reencontrar seu dragão.", 2010, 15, [anim, adv], True),
        movie("Tears of Steel", V_TOS, (TOS_IMG, TOS_IMG),
              "Em Amsterdã, cientistas tentam salvar o mundo de robôs destrutivos.", 2012, 12, [scifi], True),
        movie("Elephants Dream", V_TOS, (ED_IMG, ED_IMG),
              "Dois personagens exploram uma máquina surreal e infinita.", 2006, 12, [scifi, anim]),
    ]

    def ep(n, title, file, img):
        return {"id": _id(), "number": n, "title": title, "synopsis": f"Episódio {n} da série.",
                "duration_min": 1, "stream_url": file, "thumbnail_url": img}

    series = [{
        "id": _id(), "type": "series", "title": "Por Trás das Câmeras", "year": 2024, "rating": "L",
        "synopsis": "Curtas sobre aventuras, estradas e grandes descobertas.",
        "poster_url": U1, "backdrop_url": U1,
        "category_ids": [doc, adv], "featured": True, "active": True, "license": "Amostras abertas (Blender CC / test-videos)",
        "created_at": now_iso(),
        "seasons": [
            {"number": 1, "title": "Temporada 1", "episodes": [
                ep(1, "Fuga", V_BBB, BBB_BG),
                ep(2, "Chamas", V_SINTEL2, SINTEL_BG),
                ep(3, "Diversão", V_JELLY, U3)]},
            {"number": 2, "title": "Temporada 2", "episodes": [
                ep(1, "Passeios", V_SINTEL, SINTEL_IMG),
                ep(2, "Colapso", V_BBB, BBB_IMG)]},
        ]}, {
        "id": _id(), "type": "series", "title": "Garagem Motor", "year": 2023, "rating": "L",
        "synopsis": "Carros, estradas e desafios sobre rodas.",
        "poster_url": U2, "backdrop_url": U2,
        "category_ids": [doc], "featured": True, "active": True, "license": "Amostras abertas (Blender CC / test-videos)",
        "created_at": now_iso(),
        "seasons": [{"number": 1, "title": "Temporada 1", "episodes": [
            ep(1, "Bullrun", V_JELLY, U2),
            ep(2, "Subaru na Terra", V_SINTEL2, U4),
            ep(3, "GTI Review", V_BBB, U1)]}],
    }]
    await db.content.insert_many([dict(x) for x in movies + series])

    await db.banners.insert_many([dict(b) for b in [
        {"id": _id(), "title": "Sintel", "subtitle": "Uma jornada épica em busca de um dragão.",
         "image_url": SINTEL_BG, "content_id": movies[1]["id"], "order": 0, "active": True},
        {"id": _id(), "title": "Tears of Steel", "subtitle": "Ficção científica em Amsterdã.",
         "image_url": TOS_IMG, "content_id": movies[2]["id"], "order": 1, "active": True},
        {"id": _id(), "title": "Big Buck Bunny", "subtitle": "Diversão para toda a família.",
         "image_url": BBB_BG, "content_id": movies[0]["id"], "order": 2, "active": True},
    ]])

    await db.channels.insert_many([dict(c) for c in [
        {"id": _id(), "number": 1, "name": "PLAY Demo HD", "category": "Teste",
         "logo_url": U3, "stream_url": "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8",
         "now_playing": "Sinal de teste (HLS)", "active": True},
        {"id": _id(), "number": 2, "name": "PLAY Teste 2", "category": "Teste",
         "logo_url": U4,
         "stream_url": "https://devstreaming-cdn.apple.com/videos/streaming/examples/img_bipbop_adv_example_fmp4/master.m3u8",
         "now_playing": "Sinal de teste Apple (HLS)", "active": True},
    ]])

    # Servidores VPN: placeholders — preencher com sua infraestrutura no painel
    await db.vpn_servers.insert_many([dict(s) for s in [
        {"id": _id(), "name": "Brasil - São Paulo", "country": "BR", **VPN_DEFAULTS, "order": 0, "active": True},
        {"id": _id(), "name": "EUA - Miami", "country": "US", **VPN_DEFAULTS, "order": 1, "active": True},
    ]])


async def migrate(db):
    """Migrações idempotentes da etapa 2 (segurança)."""
    # Servidores VPN: remove configuração completa antiga (com chave privada) e aplica o novo modelo por dispositivo
    async for s in db.vpn_servers.find({}):
        upd = {k: v for k, v in VPN_DEFAULTS.items() if k not in s}
        await db.vpn_servers.update_one({"_id": s["_id"]}, {"$set": upd, "$unset": {"config": ""}} if "config" in s else {"$set": upd})
    # Administradores antigos sem a flag passam a exigir troca de senha
    await db.users.update_many({"role": "admin", "must_change_password": {"$exists": False}}, {"$set": {"must_change_password": True}})
    await db.config.update_one({"key": "app", "vpn.max_devices_per_user": {"$exists": False}}, {"$set": {"vpn.max_devices_per_user": 3}})
