import os, json, datetime

# optional daily rotation
LOG_PATH = os.getenv("REFLECTION_NOTE_PATH") or \
           f"/app/logs/reflections_{datetime.date.today():%Y%m%d}.log"

def log_reflection(reflection: dict, user_prompt: str, draft: str, final: str, session_id: str | None = None):
    """Append a reflection entry to the reflections log."""
    try:
        # 1️⃣ Make sure log directory exists
        os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)

        # 2️⃣ Ensure session_id is stored
        reflection["session_id"] = session_id or reflection.get("session_id", "unknown")

        # 3️⃣ Build JSON entry
        entry = {
            "timestamp": datetime.datetime.now().isoformat(),
            "session_id": reflection["session_id"],
            "prompt": user_prompt,
            "draft_output": draft[:500],
            "final_output": final[:500],
            "reflection": reflection,
        }

        # 4️⃣ Write it in pretty JSON, comma-delimited for easy reading
        with open(LOG_PATH, "a", encoding="utf-8") as f:
            f.write(json.dumps(entry, indent=2, ensure_ascii=False) + ",\n")

        print(f"[Cortex] Logged reflection → {LOG_PATH}")

    except Exception as e:
        print(f"[Cortex] Failed to log reflection: {e}")
