from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, Optional

from .models.gemini import Gemini
from .utils import read_json_files, get_file_by_type, prepare_answer_path


class ADFMentor:
    def __init__(self, api_key: str, model_name: str = "gemini-2.0-flash-exp", model: Optional[Gemini] = None):
        if model is None:
            model = Gemini(api_key=api_key, model_name=model_name)
        self.model = model

    def evaluate(self, answer_path: str, questions: str, prompt: str) -> Dict[str, Any]:
        """Evaluate an ADF submission against lecture tasks.

        Accepts a single .json file or a .zip archive. ZIP files are
        extracted automatically. The parsed ADF JSON is sent to the AI
        along with all lecture task descriptions so the AI can identify
        which task each file belongs to.

        Args:
            answer_path: Path to a .json file or .zip archive
            questions: Full lecture task descriptions (all tasks)
            prompt: Evaluation criteria / instructions for the AI

        Returns:
            Dictionary with 'score', 'feedback', and 'task_mapping'
        """
        working_path = prepare_answer_path(answer_path)
        path = Path(working_path)

        # Single JSON file
        if path.is_file() and path.suffix.lower() == ".json":
            adf_data = read_json_files(str(path))

        # Directory (from extracted ZIP)
        elif path.is_dir():
            json_file = get_file_by_type(working_path, ".json")
            if not json_file:
                return {
                    "score": 0,
                    "feedback": (
                        "Unable to evaluate submission.\n\n"
                        "No ADF project files (JSON) were found in the submission. "
                        "Please ensure your submission includes all required JSON files and resubmit."
                    ),
                    "task_mapping": [],
                }
            adf_data = read_json_files(str(path))
        else:
            return {
                "score": 0,
                "feedback": (
                    "Unable to evaluate submission.\n\n"
                    "No valid ADF files were found. "
                    "Please submit a .json file or a .zip archive containing your ADF project."
                ),
                "task_mapping": [],
            }

        return self.model.evaluate(
            questions=questions,
            adf_data=adf_data,
            prompt=prompt,
        )