"""
Aria Vault Indexer — Indexiert alle Obsidian Markdown-Dateien in pgvector
Kosten: ~0.02$ für 137 Dateien (text-embedding-3-small)
"""
import os
import hashlib
import json
from pathlib import Path
from openai import OpenAI
from supabase import create_client

# Config
VAULT_PATH = "/root/aria/brain"
OPENAI_KEY = os.environ.get("OPENAI_API_KEY") or open("/root/aria/.env").read().split("OPENAI_API_KEY=")[1].split("\n")[0]
SUPABASE_URL = "https://rdwtyjtotiryfvfzyafq.supabase.co"
SUPABASE_KEY = open("/root/aria/scripts/.env.aria").read().split("ARIA_SUPABASE_SERVICE_KEY=")[1].split("\n")[0].strip() if os.path.exists("/root/aria/scripts/.env.aria") else None

# Check for Supabase key in other locations
if not SUPABASE_KEY:
    for envfile in ["/root/aria/.env", "/root/aria/.env"]:
        if os.path.exists(envfile):
            content = open(envfile).read()
            if "SUPABASE_SERVICE_ROLE_KEY=" in content:
                SUPABASE_KEY = content.split("SUPABASE_SERVICE_ROLE_KEY=")[1].split("\n")[0].strip()
                break

SKIP_DIRS = {".obsidian", ".git", ".claude", "node_modules", ".next"}
EMBEDDING_MODEL = "text-embedding-3-small"

openai = OpenAI(api_key=OPENAI_KEY)

print(f"Vault: {VAULT_PATH}")
print(f"Model: {EMBEDDING_MODEL}")

# Collect all markdown files
files = []
for path in Path(VAULT_PATH).rglob("*.md"):
    if any(part in path.parts for part in SKIP_DIRS):
        continue
    files.append(path)

print(f"Found {len(files)} files to index")

# Process files
indexed = 0
skipped = 0
errors = 0
total_tokens = 0

for filepath in files:
    try:
        content = filepath.read_text(encoding="utf-8")
        if len(content.strip()) < 50:
            skipped += 1
            continue

        # Truncate very long files
        if len(content) > 8000:
            content = content[:8000]

        # Determine category from path
        rel = str(filepath.relative_to(VAULT_PATH))
        if "01-Projekte" in rel:
            category = "project"
        elif "02-Wissen" in rel:
            category = "knowledge"
        elif "03-Recherchen" in rel:
            category = "research"
        elif "13-Feedback" in rel:
            category = "feedback"
        elif "05-Referenzen" in rel:
            category = "reference"
        elif "06-Daily" in rel:
            category = "daily"
        elif rel in ["SOUL.md", "HEARTBEAT.md", "CORRECTIONS.md", "SELF-IMPROVEMENT.md"]:
            category = "system"
        else:
            category = "general"

        # Generate embedding
        response = openai.embeddings.create(
            model=EMBEDDING_MODEL,
            input=content,
        )
        embedding = response.data[0].embedding
        total_tokens += response.usage.total_tokens

        # Store in Supabase via REST API
        import requests
        res = requests.post(
            f"{SUPABASE_URL}/rest/v1/aria_memory",
            headers={
                "apikey": SUPABASE_KEY,
                "Authorization": f"Bearer {SUPABASE_KEY}",
                "Content-Type": "application/json",
                "Prefer": "return=minimal",
            },
            json={
                "content": content[:5000],
                "embedding": embedding,
                "category": category,
                "source": rel,
                "metadata": {"file": rel, "chars": len(content)},
            }
        )

        if res.status_code in (200, 201):
            indexed += 1
            if indexed % 20 == 0:
                print(f"  Progress: {indexed}/{len(files)} indexed, {total_tokens} tokens used")
        else:
            errors += 1
            if errors <= 3:
                print(f"  Error for {rel}: {res.status_code} {res.text[:100]}")

    except Exception as e:
        errors += 1
        if errors <= 3:
            print(f"  Error for {filepath.name}: {e}")

cost = total_tokens * 0.00002 / 1000  # $0.02 per 1M tokens
print(f"\nDone!")
print(f"Indexed: {indexed}")
print(f"Skipped: {skipped} (too short)")
print(f"Errors: {errors}")
print(f"Total tokens: {total_tokens}")
print(f"Estimated cost: ${cost:.4f}")
