# personality.py

import json
import os
from logger import setup_logger
logger = setup_logger("personality")

PERSONA_FILE = "persona.json"

def load_persona():
    base_dir = os.path.dirname(__file__)  # Path to /src/
    persona_path = os.path.join(base_dir, "persona.json")

    if not os.path.exists(persona_path):
        #print("⚠️ persona.json not found. Using raw LLM mode.")
        logger.info("⚠️ persona.json not found. Using raw LLM mode.")
        return None

    try:
        with open(persona_path, "r", encoding="utf-8") as f:
            data = json.load(f)
            if not data.get("name") or not data.get("prompt_inject"):
                #print("⚠️ persona.json missing fields. Using raw LLM mode.")
                logger.info("⚠️ persona.json missing fields. Using raw LLM mode.")
                return None
            return data
    except Exception as e:
        #print(f"⚠️ Failed to load persona.json: {e}")
        logger.info(f"⚠️ Failed to load persona.json: {e}")
        return None


def save_persona(description: str):
    persona = {
        "name": "Custom",
        "emoji": "🧠",
        "style_prefix": description.split(",")[0] + ":",
        "prompt_inject": description
    }
    with open(PERSONA_FILE, "w") as f:
        json.dump(persona, f, indent=2)

def apply_personality(text: str) -> str:
    persona = load_persona()
    return f"{persona['emoji']} *{persona['style_prefix']}* {text}"

def set_persona(description: str):
    save_persona(description)

