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

Version: 6.7.0
Date updated: 29/03/2026 (dd/mm/yyyy)
"""

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

# Library
# ---------------------------------------------------------------------------
from dataclasses import dataclass, field
from typing import Protocol, Self

import requests

from absfuyu.extra.gform.question_models import Question


# 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 Section:
    section_id: int
    text: str | None
    description: str | None
    page_index: int = 0
    raw: list = field(default_factory=list, repr=False)


@dataclass
class GoogleForm:
    form_id: FormID
    questions: list[Question]
    sections: list[Section] = field(default_factory=list)
    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}")

    def update_branching(self) -> None:
        """
        Update branching section id to page index
        """
        for i, q in enumerate(self.questions):
            if not q.branching:
                continue

            for k, v in q.branching.items():
                for s in self.sections:
                    if v == s.section_id:
                        self.questions[i].branching[k] = s.page_index

    # @classmethod
    # def sample_form(cls) -> Self:
    #     """
    #     Create sample test form
    #     """

    #     form = cls(
    #         form_id=FormID("sample_form"),
    #         questions=[
    #             Question(
    #                 question_id=1,
    #                 text="Question 1",
    #                 type=QuestionType.MULTIPLE_CHOICE,
    #                 entry_ids=["entry.1"],
    #                 options=["1", "2", "3"],
    #                 branching={"1": None, "2": None, "3": None},
    #             ),
    #         ],
    #     )
    #     return form


# Typing
# ---------------------------------------------------------------------------
class SupportGoogleForm(Protocol):
    def __init__(
        self, form_id: FormID, questions: list[Question], is_multipage: bool = False, page_count: int = 1
    ) -> None: ...

    def build_payload_template(self, *, default_answer: str) -> dict[str, str]: ...
