from openai import OpenAI
import pandas as pd
from tqdm import tqdm
import time
import sys
import os

client = OpenAI()

# 📥 Argumente: input și optional output
if len(sys.argv) < 2:
    print("Usage: python tagger.py input.csv [output.csv]")
    sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2] if len(sys.argv) > 2 else "tagged_comments.csv"

# 🧠 Prompt clar cu format forțat
base_prompt = """
You're a qualitative research assistant working with Reddit comments about eating behaviors, ADHD, and related medical issues.

Your task is to extract **factual thematic tags** (also called codes), similar to labels a UX researcher would use.

### Instructions:
- Read the comment carefully.
- Identify **only the concrete, observable ideas or patterns**.
- Output a list of 3–10 **short tags** (1–5 words each), such as:
  - eating for dopamine
  - nausea from hunger
  - vyvanse side effects
  - no hunger cues
  - restrictive eating disorder
  - doctor doesn’t listen
- If no such tags can be extracted, return exactly: `no actionable tags`

### Output format:
- Return the tags as a **single line**, comma-separated list.
- DO NOT use backticks, bullet points, or newlines.
- Example: eating for dopamine, nausea from hunger, vyvanse side effects

Now extract tags for this comment:
"""

# 📖 Încarcă fișierul și adaugă coloana "tags" dacă nu există
df = pd.read_csv(input_file)
if "tags" not in df.columns:
    df["tags"] = ""

# 🌀 Loop cu resume
for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing"):
    comment = str(row["comment"]).strip()

    # Skip dacă deja are taguri (resume)
    if pd.notnull(row["tags"]) and row["tags"].strip() != "":
        print('skipping row')
        continue

    full_prompt = base_prompt + "\n" + comment

    try:
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[{"role": "user", "content": full_prompt}],
            temperature=0,
            max_tokens=150
        )

        tags = response.choices[0].message.content.strip()
        df.at[idx, "tags"] = tags
        print(f"\n✅ [{idx}] {tags}")

    except Exception as e:
        df.at[idx, "tags"] = "error"
        print(f"\n❌ Error at index {idx}: {e}")

    # 📝 Salvează după fiecare comentariu
    df.to_csv(output_file, index=False)

    # 💤 Pauză pentru rate limit
    time.sleep(1.2)

print(f"\n✅ Gata! Fișierul a fost salvat în {output_file}")
