import csv
import os
from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass(frozen=True)
class Question:
    id: str
    prompt: str
    correct: str      # already lowercase, no surrounding spaces
    points: int


@dataclass(frozen=True)
class Response:
    student: str
    qid: str
    answer: Optional[str]   # None means the student left it blank


def load_rows(filename: str) -> List[dict]:
    """Read a CSV file into a list of dicts, one per row, keyed by the header."""
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
    with open(path, newline="", encoding="utf-8-sig") as f:
        return list(csv.DictReader(f))


RAW_ROWS = load_rows("responses.csv")

# From question id to Question.
QUESTIONS = {
    "q1": Question("q1", "What does len([1, 2, 3, 4]) return?", "4", 1),
    "q2": Question("q2", "Which keyword defines a function?", "def", 1),
    "q3": Question("q3", "What is 7 // 2?", "3", 1),
    "q4": Question("q4", "What does type(3.0) report?", "float", 2),
}


# ### Task 1: inspect the rows ###

# Written observations (also in your worksheet): what did you see in RAW_ROWS?


# ### Task 2: blank answers ###

def ans_is_blank(row: dict) -> bool:
    """True if the row's answer is blank: None, empty, or only spaces."""
    raise NotImplementedError


# ### Task 3: dict to dataclass ###

def to_response(row: dict) -> Response:
    """Convert a raw row to a Response: answer stripped of spaces and
    lowercased; a blank answer becomes None."""
    raise NotImplementedError


def to_responses(rows: List[dict]) -> List[Response]:
    """to_response on every row, in order."""
    raise NotImplementedError


# ### Task 4: counting by key ###

def blanks_per_question(responses: List[Response]) -> Dict[str, int]:
    """For each question that has at least one blank response, how many."""
    raise NotImplementedError


# ### Task 5: lookup ###

def points_earned(r: Response, questions: Dict[str, Question]) -> int:
    """The question's points if the answer matches its correct answer;
    0 if the answer is wrong or blank."""
    raise NotImplementedError


# ### Task 6: scoring ###

def score_by_student(responses: List[Response], questions: Dict[str, Question]) -> Dict[str, int]:
    """Total points earned per student."""
    raise NotImplementedError
