import subprocess
import sys
from pathlib import Path
import argparse

# ---------- CONFIG ----------
# Use whichever interpreter is running this script itself, rather than a
# hardcoded path to one machine's conda env. In a container there's exactly
# one Python; locally, invoke this script with the jtbd_pipeline env's python
# (e.g. `/path/to/envs/jtbd_pipeline/bin/python run_jtbd_pipeline.py ...`) and
# every subprocess step below will correctly reuse that same interpreter.
ENV_PYTHON = sys.executable

# ---------- UTILS ----------
def run_command(command):
    """Run a command using the jtbd_pipeline env's python directly."""
    full_command = command.replace("python ", f"{ENV_PYTHON} ", 1)

    print(f"\n🔹 Running: {full_command}")
    result = subprocess.run(full_command, shell=True)
    if result.returncode != 0:
        print(f"❌ Error: Command failed -> {command}")
        sys.exit(1)
    print(f"✅ Finished: {command}\n")

# ---------- MAIN PIPELINE ----------
def main(input_file, from_step=1):
    input_path = Path(input_file)
    if not input_path.exists():
        print(f"❌ Input file not found: {input_file}")
        sys.exit(1)

    base = input_path.stem

    steps = [
        (1, "Extract emotions",
         f"python extract_push_emotions.py {input_file}"),
        (2, "Keep JTBD sentences",
         f"python keep_jtbd_sentences.py {base}_audience_forces.csv {base}_jtbd_candidates.csv"),
        (3, "Extract JTBD statements",
         f"python jtbd_sample_print.py {base}_jtbd_candidates.csv {base}_jtbd_comments.csv"),
        (4, "Cluster situation/struggle/outcome into semantic themes",
         f"python jtbd_tag_cloud_noun_phrases.py -i {base}_jtbd_comments.csv"),
        (5, "Extract contexts",
         f"python extract_contexts.py {base}_jtbd_comments.csv comment"),
        (6, "Identify value opportunities",
         f"python jtbd_value_opportunity.py --input={base}_jtbd_comments__jtbd_archetypes.csv"),
        (7, "Extract trigger verbs & journey stages",
         f"python extract_trigger_verbs.py {base}_jtbd_comments__jtbd_archetypes.csv"),
        (8, "Cluster current approaches & hesitations",
         f"python extract_approach_and_hesitation_clusters.py {base}_jtbd_comments__jtbd_archetypes.csv"),
        (9, "Extract pain points from JTBD comments",
         f"python extract_pain_points.py --input={base}_jtbd_comments.csv --output={base}_pain_points.csv"),
        (10, "Cluster pain points into themes",
         f"python coalesce_pain_points.py {base}_pain_points.csv"),
        (11, "Generate market report",
         f"python generate_market_report.py {base}")
    ]

    print(f"\n🚀 Starting JTBD pipeline from step {from_step}...\n")

    for step_num, desc, command in steps:
        if step_num >= from_step:
            print(f"=== STEP {step_num}: {desc} ===")
            run_command(command)
        else:
            print(f"⏭️  Skipping step {step_num}: {desc}")

    print("\n✅ Pipeline completed successfully!\n")

# ---------- ENTRY POINT ----------
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run the JTBD pipeline from any step.")
    parser.add_argument("input_file", help="Path to the input comments CSV file.")
    parser.add_argument("--from-step", "-s", type=int, default=1, help="Step number to start from (default: 1).")
    args = parser.parse_args()

    main(args.input_file, args.from_step)
