"""
Evaluate EROM JTBD Relevance (Manager Context, Resumable Version)

This script:
1. Reads a CSV file with columns: situation, struggle, outcome (end-user JTBDs).
2. Interprets each JTBD from the manager / decision-maker perspective.
3. Classifies relevance to EROM.
4. Extracts the managerial problem created by the user’s struggle.
5. Saves results incrementally and resumes if restarted.

Requirements:
- openai >= 1.0.0
- Python 3.9+
- Environment variable: OPENAI_API_KEY
"""

from openai import OpenAI
import csv
import json
import time
import os
import sys

# === CONFIGURATION ===

if len(sys.argv) < 2:
    print("Usage: python script.py <input_file>")
    sys.exit(1)

INPUT_FILE = sys.argv[1]
base, ext = os.path.splitext(INPUT_FILE)
OUTPUT_FILE = f"{base}_manager_evaluated{ext}"

MODEL_NAME = "gpt-5"
TEMPERATURE = 0.2
DELAY_BETWEEN_CALLS = 1.5

print(f"Input: {INPUT_FILE}")
print(f"Output: {OUTPUT_FILE}")

# === OPENAI CLIENT ===
client = OpenAI()

# === SYSTEM PROMPT ===
SYSTEM_PROMPT = """
You are an expert in operational leadership, business process automation, and organizational risk.

You are evaluating “Jobs to Be Done” (JTBD) statements written from the end user’s perspective.
Your task is to interpret each JTBD from the perspective of the **manager, director, or operational leader** who:
- Oversees these users
- Is accountable for outcomes
- Owns budget and tooling decisions

Your job:

1. Translate the end-user JTBD into the **manager’s problem**:
   - What operational pain, risk, or inefficiency does this create?
   - What breaks at scale?
   - Where does oversight fail?
   - Why does this matter to the manager’s KPIs?

2. Classify relevance to EROM strictly based on real capabilities.

EROM is:
- A business orchestration and automation platform
- Used to coordinate people, systems, AI agents, and data
- Strong in workflow orchestration, intake management, approvals, escalations, SOP enforcement, auditability, and AI-governed operations

EROM is not:
- An RPA screen-scraping tool
- A replacement for ERP or CRM
- A no-code website builder or social platform

3. Return output strictly as JSON with the following keys:

{
  "Managerial_Problem": "<What problem this creates for the manager>",
  "Relevance": "✅ Directly relevant" | "⚙️ Partially relevant" | "❌ Not relevant",
  "Reasoning": "<Why from the manager’s POV>",
  "potential_use_case": "<Short example of how EROM could help, or null>"
}

Keep responses concise and concrete.
"""

# === FUNCTIONS ===

def load_existing_results(output_file):
    """Load already-processed rows to allow resuming."""
    if not os.path.exists(output_file):
        return set()

    processed = set()
    with open(output_file, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            processed.add(row["situation"])

    return processed


def evaluate_jtbd_row(row):
    """Send a JTBD row to the GPT model and return parsed JSON result."""
    user_prompt = f"""
Situation: {row['situation']}
Struggle: {row['struggle']}
Outcome: {row['outcome']}
"""

    try:
        params = {
            "model": MODEL_NAME,
            "messages": [
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": user_prompt}
            ],
            "response_format": {"type": "json_object"},
        }

        if MODEL_NAME not in {"gpt-4.1", "gpt-5"}:
            params["temperature"] = TEMPERATURE

        response = client.chat.completions.create(**params)

        content = response.choices[0].message.content.strip()
        data = json.loads(content)

        return {
            "situation": row["situation"],
            "managerial_problem": data.get("Managerial_Problem", ""),
            "relevance": data.get("Relevance", ""),
            "reasoning": data.get("Reasoning", ""),
            "potential_use_case": data.get("potential_use_case", "")
        }

    except Exception as e:
        print(f"⚠️ Error processing row '{row.get('situation', '')[:60]}...': {e}")
        return {
            "situation": row["situation"],
            "managerial_problem": "",
            "relevance": "ERROR",
            "reasoning": str(e),
            "potential_use_case": ""
        }


def main():
    print(f"🚀 Starting EROM JTBD MANAGER-CONTEXT evaluation with model: {MODEL_NAME}")

    with open(INPUT_FILE, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        rows = list(reader)

    processed = load_existing_results(OUTPUT_FILE)
    print(f"🔄 Found {len(processed)} rows already processed. Will skip them.\n")

    file_exists = os.path.exists(OUTPUT_FILE)

    with open(OUTPUT_FILE, "a", newline='', encoding='utf-8') as f:
        fieldnames = [
            "situation",
            "managerial_problem",
            "relevance",
            "reasoning",
            "potential_use_case"
        ]
        writer = csv.DictWriter(f, fieldnames=fieldnames)

        if not file_exists:
            writer.writeheader()

        for i, row in enumerate(rows, 1):
            if row["situation"] in processed:
                continue

            print(f"[{i}/{len(rows)}] Processing: {row['situation'][:80]}...")
            result = evaluate_jtbd_row(row)
            writer.writerow(result)
            f.flush()
            time.sleep(DELAY_BETWEEN_CALLS)

    print(f"\n✅ Done! Results saved to {OUTPUT_FILE}")


if __name__ == "__main__":
    main()
