"""Load paths, prompts, Notion parent, optional notebook id."""

from __future__ import annotations

import os
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any

from folio_notion.config_load import load_config
from folio_notion.envfile import load_dotenv
from folio_notion.integrations.notebooklm.paths import get_storage_path

if TYPE_CHECKING:
    from folio_notion.pipeline_context import PipelineContext


def _as_float(val: Any, default: float) -> float:
    if val is None:
        return default
    try:
        return float(val)
    except (TypeError, ValueError):
        return default


def _as_int(val: Any, default: int) -> int:
    if val is None:
        return default
    try:
        return int(val)
    except (TypeError, ValueError):
        return default


def run(ctx: PipelineContext) -> None:
    env_path = ctx.project_root / ".env"
    load_dotenv(env_path)

    ctx.config = load_config(ctx.project_root)

    inp = ctx.config.get("input_dir", "./var/inbox")
    out = ctx.config.get("export_dir", "./var/exports")
    ctx.config["input_dir"] = str((ctx.project_root / inp).resolve())
    ctx.config["export_dir"] = str((ctx.project_root / out).resolve())

    prompts = ctx.config.get("prompts") or {}
    ctx.synthesis_prompt = str(prompts.get("synthesis") or "Summarize the uploaded sources.")

    notion = ctx.config.get("notion") or {}
    ctx.notion_parent_id = (notion.get("parent_page_id") or os.environ.get("NOTION_PARENT_PAGE_ID") or "").strip()
    ctx.notion_api_max_retries = max(
        0, _as_int(notion.get("api_max_retries"), ctx.notion_api_max_retries)
    )

    ctx.notion_token = (os.environ.get("NOTION_TOKEN") or "").strip()

    sp = os.environ.get("FOLIO_NOTEBOOKLM_STORAGE", "").strip()
    ctx.notebooklm_storage = Path(sp).expanduser().resolve() if sp else get_storage_path()

    ctx.run_title = f"Folio — {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M')} UTC"

    nbl = ctx.config.get("notebooklm") or {}
    nid = nbl.get("notebook_id")
    if nid is not None and str(nid).strip():
        ctx.notebooklm_notebook_id = str(nid).strip()
    else:
        ctx.notebooklm_notebook_id = None

    ctx.notebooklm_source_upload_timeout_sec = max(
        1.0,
        _as_float(
            nbl.get("source_upload_timeout_sec"),
            ctx.notebooklm_source_upload_timeout_sec,
        ),
    )
    ctx.notebooklm_post_upload_wait_sec = max(
        0.0,
        _as_float(
            nbl.get("post_upload_wait_sec"),
            ctx.notebooklm_post_upload_wait_sec,
        ),
    )
    ctx.notebooklm_chat_retries = max(
        0,
        _as_int(nbl.get("chat_retries"), ctx.notebooklm_chat_retries),
    )
    ctx.notebooklm_chat_retry_delay_sec = max(
        0.0,
        _as_float(nbl.get("chat_retry_delay_sec"), ctx.notebooklm_chat_retry_delay_sec),
    )
