import json
import sys
from agent import CareerAgent

# Configuration for supported platforms
VALID_PLATFORMS = {
    "youtube": "youtube.com",
    "google": "google.com",
    "coursera": "coursera.org",
    "khan_academy": "khanacademy.org"
}


def fetch_courses_with_agent(user_skills, user_query, platform_name, job_profile_data=None):
    """Fetch courses using the CareerAgent with job profile data."""
    agent = CareerAgent(user_skills, user_query, platform_name, job_profile_data)
    return agent.recommend_courses(agent.fetch_courses())

def process_input_file(file_path):
    """Process the input JSON file and generate recommendations."""
    try:
        with open(file_path, 'r') as f:
            input_data = json.load(f)

        return generate_recommendations_from_data(input_data)
    except Exception as e:
        print(f"Error processing input file: {str(e)}")
        return {"online_courses": []}

def generate_recommendations_from_data(input_data):
    """Process input data directly and generate recommendations."""
    try:
        user_id = list(input_data["user_data"].keys())[0]
        user_info = input_data["user_data"][user_id]
        user_skills = user_info["skills"]
        user_query = input_data["user_query"]
        platform_name = input_data["platform_name"]
        
        # Extract job profile data - handle case when it's not available
        job_profile_data = user_info.get("jobProfile", None)
        
        # If job profile data is empty or None, set it to None for the agent
        if job_profile_data and not job_profile_data.get("job_profile_name"):
            job_profile_data = None
        
        # Fetch courses using the agent with job profile data (can be None)
        online_courses = fetch_courses_with_agent(user_skills, user_query, platform_name, job_profile_data)

        response = {
            "online_course_recommendations": online_courses
        }

        return response
    except Exception as e:
        print(f"Error processing input data: {str(e)}")
        return {"online_course_recommendations": []}

def supported_platforms():
    """Returns a list of all supported platforms."""
    return sorted(VALID_PLATFORMS.keys())

if __name__ == "__main__":
    if len(sys.argv) == 1:
        sample_data = {
            "client_id": "3",
            "user_query": "Suggest suitable career path for my skills and completed courses.",
            "platform_name": "youtube",
            "user_data": {
                "4": {
                    "user_name": "Kunal Jain",
                    "managerId": "13962",
                    "designation": "Engineer",
                    "jobProfile": {
                        "job_profile_name": "data scientist",
                        "job_profile_skills": [
                            { "skill_id": "20", "skill_type": "1", "skill_name": "Machine Learning" },
                            { "skill_id": "15", "skill_type": "1", "skill_name": "Python" },
                            { "skill_id": "17", "skill_type": "1", "skill_name": "Deep Learning" }
                        ]
                    },
                    "assignedCourses": ["6", "5", "62", "98", "82", "291", "455", "433", "353", "580"],
                    "completedCourses": ["111", "114"],
                    "skills": [
                        { "skill_id": "6", "skill_type": "3", "skill_name": "Leadership" },
                        { "skill_id": "7", "skill_type": "1", "skill_name": "Management" },
                        { "skill_id": "9", "skill_type": "2", "skill_name": "Communication" },
                        { "skill_id": "242", "skill_type": "3", "skill_name": "Project Management" },
                        { "skill_id": "26", "skill_type": "2", "skill_name": "Teamwork" },
                        { "skill_id": "8", "skill_type": "1", "skill_name": "Problem Solving" },
                        { "skill_id": "5", "skill_type": "2", "skill_name": "Time Management" },
                        { "skill_id": "190", "skill_type": "2", "skill_name": "Analytical Skills" },
                        { "skill_id": "70", "skill_type": "1", "skill_name": "Creativity" },
                        { "skill_id": "224", "skill_type": "1", "skill_name": "Adaptability" },
                        { "skill_id": "252", "skill_type": "1", "skill_name": "Innovation" },
                        { "skill_id": "234", "skill_type": "2", "skill_name": "Strategic Thinking" },
                        { "skill_id": "241", "skill_type": "1", "skill_name": "Decision Making" }
                    ]
                }
            }
        }

        result = generate_recommendations_from_data(sample_data)
        print(json.dumps(result, indent=2))

        print("\nSupported platforms:")
        for platform in supported_platforms():
            print(f"- {platform}")

    elif len(sys.argv) == 2:
        result = process_input_file(sys.argv[1])
        print(json.dumps(result, indent=2))

    else:
        print("Usage: python script.py [input_file.json]")
        print("If no input file is provided, sample data will be used.")
        print("\nSupported platforms:")
        for platform in supported_platforms():
            print(f"- {platform}")