import asyncio
import json
import os
import sys

# Path to the orchestrator
sys.path.append(os.path.join(os.getcwd(), 'competitor-analysis-app'))

from competitor_analysis_orchestrator import analyze_single_competitor, fetch_step7_data_battlecards, FetchStep7DataBattlecardsRequest

# Mock Object to mimic Pydantic model behavior for the API call
class MockCompany:
    def __init__(self, data):
        self.name = data.get('name')
        self.start_url = data.get('start_url')
    def get(self, key, default=None):
        return getattr(self, key, default)

class MockRequest:
    def __init__(self, company, analyses, silver_bullets):
        self.company = company
        self.analyses = analyses
        self.silver_bullets = silver_bullets
        self.language = "de"

async def refresh_classification():
    json_path = 'analysis_robo-planet.de.json'
    
    with open(json_path, 'r') as f:
        data = json.load(f)
        
    company_data = data.get('company', {})
    competitors = data.get('competitors_shortlist', []) or data.get('competitor_candidates', [])
    silver_bullets = data.get('silver_bullets', [])

    print(f"🔄 Re-Running Classification for {len(competitors)} competitors...")
    
    # --- STEP 1: Re-Analyze Single Competitors (to get Product Categories) ---
    print("Step 1: Updating Portfolio Classification...")
    tasks = [analyze_single_competitor(c, company_data) for c in competitors]
    new_analyses = await asyncio.gather(*tasks)
    
    # Filter valid results
    valid_analyses = [r for r in new_analyses if r is not None]
    data['analyses'] = valid_analyses
    print(f"✅ Updated {len(valid_analyses)} analyses with product categories.")

    # --- STEP 2: Re-Generate Battlecards (to get Landmine Topics) ---
    print("Step 2: Updating Battlecard Classification...")
    
    # Construct request object for the API function
    # Note: fetch_step7_data_battlecards expects a Pydantic model, but we can pass a dict if we are careful or construct a mock.
    # The function uses `request.analyses` etc.
    
    req = FetchStep7DataBattlecardsRequest(
        company=company_data,
        analyses=valid_analyses,
        silver_bullets=silver_bullets,
        language="de"
    )
    
    # Call the function directly
    new_battlecards_result = await fetch_step7_data_battlecards(req)
    
    if new_battlecards_result and 'battlecards' in new_battlecards_result:
        data['battlecards'] = new_battlecards_result['battlecards']
        print(f"✅ Updated {len(data['battlecards'])} battlecards with topics.")
    else:
        print("⚠️ Failed to update battlecards.")

    # Save
    with open(json_path, 'w') as f:
        json.dump(data, f, indent=2)
        
    print(f"🎉 Successfully updated {json_path} with full classification.")

if __name__ == "__main__":
    asyncio.run(refresh_classification())
