"""View all feedback scores from Langfuse - output to file"""
import requests, json
from collections import defaultdict

BASE = "http://172.16.2.207:3009"
AUTH = ("pk-lf-2bb249b1-77e3-4309-8954-312b8fb2fff9", "sk-lf-bd0c7202-a7f4-4399-a36e-65ebe2e35104")

lines = []
def p(s=""): lines.append(s)

p("=" * 70)
p("  LANGFUSE FEEDBACK SCORES REPORT")
p("=" * 70)

# All scores
r = requests.get(f"{BASE}/api/public/scores?limit=50", auth=AUTH, timeout=10)
scores = r.json().get("data", []) if r.status_code == 200 else []
p(f"\nTotal scores in Langfuse: {len(scores)}\n")

# Group by trace
by_trace = defaultdict(list)
for s in scores:
    by_trace[s["traceId"]].append(s)

# Feedback-related scores
fb_traces = {}
for tid, slist in by_trace.items():
    fb = [s for s in slist if s["name"].startswith("user-feedback") or s["name"].startswith("feedback-")]
    if fb:
        fb_traces[tid] = fb

if fb_traces:
    p(f"Traces with FEEDBACK scores: {len(fb_traces)}\n")
    for tid, slist in fb_traces.items():
        p(f"  Trace: {tid}")
        for s in slist:
            val = s.get("stringValue") or s.get("value", "")
            p(f"    {s['name']:25s} = {str(val):15s} | {s.get('dataType','?'):12s} | {s.get('comment','')}")
        p(f"    URL: {BASE}/project/cmk3i5l310008r407rsiib2h4/traces/{tid}")
        p()
else:
    p("  No feedback scores found!\n")

p("-" * 70)
p("ALL scores:\n")
for s in scores:
    val = s.get("stringValue") or s.get("value", "")
    p(f"  {s['name']:25s} = {str(val):15s} | {s.get('dataType','?'):12s} | trace={s['traceId'][:24]}...")

p(f"\n{'=' * 70}")
p(f"Langfuse Scores URL: {BASE}/project/cmk3i5l310008r407rsiib2h4/scores")

# Write to file
output = "\n".join(lines)
with open("d:/cnf/chatbot-canifa-feedback/backend/langfuse_report.txt", "w", encoding="utf-8") as f:
    f.write(output)

print("Report saved to langfuse_report.txt")
