# user_profiles.py
# Handles loading, updating, and storing per-user profiles for Delta

import os
import json
from datetime import datetime

PROFILE_PATH = os.path.join(os.path.dirname(__file__), "user_profiles.json")

def ensure_profile_file():
    """Ensure the JSON file exists and is a dict"""
    if not os.path.exists(PROFILE_PATH):
        with open(PROFILE_PATH, "w", encoding="utf-8") as f:
            json.dump({}, f, indent=2)
    else:
        try:
            with open(PROFILE_PATH, "r", encoding="utf-8") as f:
                if not isinstance(json.load(f), dict):
                    raise ValueError
        except Exception:
            with open(PROFILE_PATH, "w", encoding="utf-8") as f:
                json.dump({}, f, indent=2)

def load_profiles():
    ensure_profile_file()
    with open(PROFILE_PATH, "r", encoding="utf-8") as f:
        return json.load(f)

def save_profiles(profiles):
    with open(PROFILE_PATH, "w", encoding="utf-8") as f:
        json.dump(profiles, f, indent=2)

def load_user_profile(user):
    ensure_profile_file()
    profiles = load_profiles()
    uid = str(user.id)
    now = datetime.utcnow().isoformat()

    profile = profiles.get(uid, {
        "name": user.name,
        "display_name": user.display_name,
        "first_seen": now,
        "last_seen": now,
        "last_message": now,
        "interactions": 0,
        "pronouns": None,
        "avatar_url": str(user.display_avatar.url),
        "custom_prompt": None  # 🆕 field
    })

    # Always update timestamp + count
    profile["last_seen"] = now
    profile["last_message"] = now
    profile["interactions"] += 1

    profiles[uid] = profile
    save_profiles(profiles)
    return profile

def update_last_seen(user_id):
    profiles = load_profiles()
    uid = str(user_id)
    if uid in profiles:
        profiles[uid]["last_seen"] = datetime.utcnow().isoformat()
        save_profiles(profiles)

def increment_interactions(user_id):
    profiles = load_profiles()
    uid = str(user_id)
    if uid in profiles:
        profiles[uid]["interactions"] += 1
        save_profiles(profiles)

def set_pronouns(user, pronouns):
    profiles = load_profiles()
    uid = str(user.id)
    profile = load_user_profile(user)
    profile["pronouns"] = pronouns
    profiles[uid] = profile
    save_profiles(profiles)
    return True

def set_custom_prompt(user_id, prompt):
    profiles = load_profiles()
    uid = str(user_id)
    if uid in profiles:
        profiles[uid]["custom_prompt"] = prompt
        save_profiles(profiles)

def format_profile_for_block(profile):
    lines = ["[User Profile]"]
    lines.append(f"- Name: {profile['display_name']}")
    if profile.get("pronouns"):
        lines.append(f"- Pronouns: {profile['pronouns']}")
    lines.append(f"- Interactions: {profile['interactions']}")
    if profile.get("custom_prompt"):
        lines.append(f"- Custom Prompt: {profile['custom_prompt']}")
    return "\n".join(lines)


