# -*- coding: utf-8 -*-
import requests
import os
import time

# --- AUTH CONFIG ---
SUPABASE_URL = 'https://vvcwjlcequbkhlpmwzlc.supabase.co'
SUPABASE_KEY = 'sb_secret_0JKcTXZGPk253MHYeSXY1A_scBtozEB'
HEADERS = {'apikey': SUPABASE_KEY, 'Authorization': f'Bearer {SUPABASE_KEY}', 'Content-Type': 'application/json'}

# --- VPS ASSET CONFIG ---
ASSET_ROOT = r"C:\gasp_assets"
BASE_URL = "https://asset.gasp.fun"

def migrate_posts():
    print("?? Starting Post Migration: Supabase Storage -> VPS...")
    # 1. Get all posts with supabase URLs
    res = requests.get(f"{SUPABASE_URL}/rest/v1/posts?content_url=like.*supabase.co*&select=id,persona_id,content_url", headers=HEADERS)
    posts = res.json()
    print(f"   Found {len(posts)} posts to migrate.")

    for post in posts:
        old_url = post['content_url']
        pid = post['persona_id']
        filename = old_url.split('/')[-1]
        
        # Determine persona name (for folder structure)
        p_name = pid.split('-')[0].lower() # Simple heuristic for your persona IDs
        
        persona_path = os.path.join(ASSET_ROOT, p_name)
        if not os.path.exists(persona_path): os.makedirs(persona_path)
        
        dest_path = os.path.join(persona_path, filename)
        
        print(f"   ?? Migrating: {filename}...")
        try:
            # Download
            img_res = requests.get(old_url, timeout=30)
            if img_res.status_code == 200:
                with open(dest_path, 'wb') as f:
                    f.write(img_res.content)
                
                # Update DB
                new_url = f"{BASE_URL}/{p_name}/{filename}"
                requests.patch(f"{SUPABASE_URL}/rest/v1/posts?id=eq.{post['id']}", headers=HEADERS, json={"content_url": new_url})
                print(f"   ? Done: {new_url}")
            else:
                print(f"   ?? Failed Download: {old_url}")
        except Exception as e:
            print(f"   ? Error: {e}")

def migrate_personas():
    print("\n?? Starting Persona Migration: Supabase Storage -> VPS...")
    res = requests.get(f"{SUPABASE_URL}/rest/v1/personas?seed_image_url=like.*supabase.co*&select=id,name,seed_image_url", headers=HEADERS)
    personas = res.json()
    print(f"   Found {len(personas)} personas to migrate.")

    for p in personas:
        old_url = p['seed_image_url']
        name = p['name'].lower()
        filename = old_url.split('/')[-1]
        
        persona_path = os.path.join(ASSET_ROOT, name)
        if not os.path.exists(persona_path): os.makedirs(persona_path)
        
        dest_path = os.path.join(persona_path, filename)
        
        print(f"   ?? Migrating Seed: {filename}...")
        try:
            img_res = requests.get(old_url, timeout=30)
            if img_res.status_code == 200:
                with open(dest_path, 'wb') as f:
                    f.write(img_res.content)
                
                new_url = f"{BASE_URL}/{name}/{filename}"
                requests.patch(f"{SUPABASE_URL}/rest/v1/personas?id=eq.{p['id']}", headers=HEADERS, json={"seed_image_url": new_url})
                print(f"   ? Done: {new_url}")
        except Exception as e:
             print(f"   ? Error: {e}")

if __name__ == "__main__":
    if not os.path.exists(ASSET_ROOT): os.makedirs(ASSET_ROOT)
    migrate_posts()
    migrate_personas()
    print("\n?? MIGRATION COMPLETE: ALL SUPABASE ASSETS NOW SERVED BY VPS/CLOUDFLARE LAYER")
