# ASTA TREBUIE RULAT PRIMUL PE LISTA DE COMENTARII DINTR-UN CLUSTER

import os
from openai import OpenAI
from textwrap import dedent
import sys

# Init client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

import sys
import csv

INPUT_FILE = sys.argv[1]
CHUNK_SIZE = 25  # adjust based on your average comment length

# Load comments from CSV (assuming header with a column "comment")
comments = []
with open(INPUT_FILE, "r", encoding="utf-8", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row.get("comment"):
            comments.append(row["comment"].strip())

# Split comments into chunks
chunks = [comments[i:i + CHUNK_SIZE] for i in range(0, len(comments), CHUNK_SIZE)]

def summarize_chunk(chunk, idx):
    prompt = f"""
    I have a set of user comments (chunk {idx}). Please generate a structured Jobs To Be Done (JTBD) summary.

    Use this format:
    "When I [situation], but [struggle], I want to [goal], so I can [desired outcome]."

    Also list the forces of progress: Push, Pull, Anxieties, Habits.

    Comments:
    {chr(10).join(chunk)}
    """
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": dedent(prompt)}],
        temperature=0.7
    )
    return response.choices[0].message.content.strip()

# Step 1: Summarize each chunk
chunk_summaries = []
for i, chunk in enumerate(chunks, start=1):
    summary = summarize_chunk(chunk, i)
    print(f"\n=== Chunk {i} Summary ===\n{summary}\n")
    chunk_summaries.append(summary)

# Step 2: Merge into a master JTBD
merge_prompt = f"""
I have several JTBD summaries from different chunks of comments. 
Please synthesize them into ONE master JTBD problem statement + forces of progress.

Chunk summaries:
{chr(10).join(chunk_summaries)}
"""

final = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": dedent(merge_prompt)}],
    temperature=0.7
)

print("\n=== Final Master JTBD Statement ===\n")
print(final.choices[0].message.content.strip())
