import json
import os
import sys
import pandas as pd
from pathlib import Path
from dotenv import load_dotenv
from tqdm import tqdm

# Add ml_service root to path
ML_SERVICE_ROOT = str(Path(__file__).resolve().parents[2])
if ML_SERVICE_ROOT not in sys.path:
    sys.path.insert(0, ML_SERVICE_ROOT)

# Load environment variables
load_dotenv(Path(ML_SERVICE_ROOT) / ".env")

from app.models.predictor import ModelPredictor

def main():
    print("Starting business evaluation...")
    
    # Paths
    EVAL_DIR = Path(__file__).resolve().parent
    DATA_CSV = EVAL_DIR / "synthetic_businesses.csv"
    OUTPUT_JSON = EVAL_DIR / "business_predictions.json"
    
    if not DATA_CSV.exists():
        print(f"Error: {DATA_CSV} not found!")
        return
        
    # Initialize Predictor
    try:
        predictor = ModelPredictor()
        print("ModelPredictor initialized successfully.")
    except Exception as e:
        print(f"Failed to initialize ModelPredictor: {e}")
        return

    # Load Data
    df = pd.read_csv(DATA_CSV)
    print(f"Loaded {len(df)} businesses from {DATA_CSV}")
    
    # Load Existing Results for Resuming
    results = []
    processed_businesses = set()
    if OUTPUT_JSON.exists():
        try:
            with open(OUTPUT_JSON, "r", encoding="utf-8") as f:
                results = json.load(f)
                processed_businesses = {r['business_name'] for r in results}
            print(f"Found {len(results)} existing predictions. Resuming...")
        except Exception as e:
            print(f"Warning: Could not load existing results for resuming: {e}")
    
    # Process Data
    for _, row in tqdm(df.iterrows(), total=len(df), desc="Predicting Businesses"):
        business_name = row['business_name']
        
        if business_name in processed_businesses:
            continue
            
        description = row['business_description']
        budget_min = row['budget_min']
        budget_max = row['budget_max']
        
        try:
            prediction = predictor.predict_business(
                business_description=description,
                budget_min=budget_min,
                budget_max=budget_max
            )
            
            if prediction:
                result = {
                    "business_name": business_name,
                    "description": description,
                    "budget_min": budget_min,
                    "budget_max": budget_max,
                    "prediction": prediction
                }
                results.append(result)
                
                # Save Progress after each success
                with open(OUTPUT_JSON, "w", encoding="utf-8") as f:
                    json.dump(results, f, indent=2)
            else:
                print(f"  Warning: Prediction failed for {business_name}")
                
        except Exception as e:
            print(f"  Error processing {business_name}: {e}")
            
    print(f"\nSaved {len(results)} predictions to {OUTPUT_JSON}")
    print("Business evaluation complete!")

if __name__ == "__main__":
    main()
