import logging
import sys
from functools import partial

import streamlit as st
import structlog

from csirtmu.self_service import models

logger: logging.Logger = structlog.getLogger()


@st.cache_resource
def first_step(language: str) -> models.TextStep | None:
    return st.session_state.client.get_first_step(language)


@st.cache_resource
def get_next_steps(
    language: str,
    step_id: int,
    version: str,  # noqa: ARG001
) -> list[models.TextStep | models.LinkStep | models.FormStep | models.NetboxSearchStep | models.OutlineSearchStep]:
    return st.session_state.client.get_next_step(language, step_id)


def main() -> None:
    translation = st.session_state["translations"][st.session_state["language"]]
    step = first_step(st.session_state.language)
    if not step:
        logger.info("NO STEP FOUND")
        sys.exit(1)

    st.title(translation["main_page"]["title"])

    i = 1
    while True:
        if isinstance(step, models.FormStep):
            step.subscribe_on_form_submit(partial(st.session_state.client.submit_form))
        elif isinstance(step, models.NetboxSearchStep):
            step.subscribe_on_search(partial(st.session_state.client.search_netbox))
        elif isinstance(step, models.OutlineSearchStep):
            step.subscribe_on_search(partial(st.session_state.client.search_outline))
        step.display()

        next_steps = get_next_steps(st.session_state.language, step.id, st.session_state["version"])
        if len(next_steps) == 0:
            st.divider()
            st.text(translation["main_page"]["end"])
            break

        next_step_options = [s.title for s in next_steps]
        option = st.selectbox(
            translation["main_page"]["next"],
            next_step_options,
            index=None,
            placeholder=translation["main_page"]["placeholder"],
            key=step.id,
        )

        if option is None:
            break

        i += 1
        step = next_steps[next_step_options.index(option)]
        st.divider()


if st.session_state.page == 0:
    main()
