"""
Absfuyu: Google form
--------------------
Google form - Model

Version: 6.5.0
Date updated: 19/03/2026 (dd/mm/yyyy)
"""

# Module level
# ---------------------------------------------------------------------------
__all__ = [
    "QuestionType",
    "FormID",
    "Question",
    "GoogleForm",
]

# Library
# ---------------------------------------------------------------------------
from dataclasses import dataclass, field
from enum import Enum
from typing import Self

import requests


# Enum
# ---------------------------------------------------------------------------
class QuestionType(Enum):
    SHORT_ANSWER = 0
    PARAGRAPH = 1
    MULTIPLE_CHOICE = 2
    DROPDOWN = 3
    CHECKBOXES = 4
    LINEAR_SCALE = 5
    GRID = 7
    SECTION = 8
    DATE = 9
    TIME = 10
    UNKNOWN = -1

    @classmethod
    def from_code(cls, code: int):
        return cls(code) if code in cls._value2member_map_ else cls.UNKNOWN


# Model
# ---------------------------------------------------------------------------
@dataclass
class FormID:
    form_id: str

    @property
    def view(self) -> str:
        return f"https://docs.google.com/forms/d/e/{self.form_id}/viewform"

    @property
    def response(self) -> str:
        return f"https://docs.google.com/forms/d/e/{self.form_id}/formResponse"

    @classmethod
    def from_link(cls, link: str) -> Self:
        id_ = link.split("https://docs.google.com/forms/d/e/")[-1].split("/")[0]
        return cls(id_)


@dataclass
class Question:
    question_id: int
    text: str
    type: QuestionType
    entry_ids: list[str]
    options: list[str] = field(default_factory=list)

    # Branching
    # option_text -> target_page
    branching: dict[str, int | None] = field(default_factory=dict)
    page_index: int = 0


@dataclass
class GoogleForm:
    form_id: FormID
    questions: list[Question]
    is_multipage: bool = False
    page_count: int = 1

    def build_page_history(self) -> str:
        return ",".join(map(str, range(self.page_count)))

    def build_payload_template(self, *, default_answer: str = "YOUR_ANSWER_HERE") -> dict[str, str]:
        payload = {}
        for q in self.questions:
            for entry in q.entry_ids:
                payload[entry] = default_answer

        if self.is_multipage:
            payload["pageHistory"] = self.build_page_history()
        return payload

    def submit(self, data: dict[str, str]) -> None:
        """Submit form to url with data"""
        res = requests.post(self.form_id.response, data=data, timeout=5)
        if res.status_code != 200:
            raise TimeoutError(f"Can't submit form - {res.status_code}")

    @classmethod
    def submit2(cls, form_link: str, data: dict[str, str]) -> None:
        """Submit form (standalone version)"""
        res = requests.post(form_link, data=data, timeout=5)
        if res.status_code != 200:
            raise TimeoutError(f"Can't submit form - {res.status_code}")
