"""High-level API for fetching and rendering materials."""

import os
from typing import Optional, Tuple

import pyvista as pv
from mp_api.client import MPRester

from ceraviz.structure import extract_materials
from ceraviz.renderer import view_crystal


def _resolve_api_key(api_key: Optional[str] = None) -> str:
    """Resolve API key from argument, environment variable, or stored config.

    Priority: explicit argument > MP_API_KEY env var > stored config file.
    Raises ValueError if no key is found.
    """
    from ceraviz.config import get_stored_api_key

    key = api_key or os.environ.get("MP_API_KEY") or get_stored_api_key()
    if not key:
        raise ValueError(
            "No Materials Project API key provided. "
            "Either pass api_key=, set the MP_API_KEY environment variable, "
            "or run 'ceraviz' to set up your key interactively. "
            "Get a free key at https://next-gen.materialsproject.org/api"
        )
    return key


def render_material(
    material_id: str,
    api_key: Optional[str] = None,
    supercell: Tuple[int, int, int] = (1, 1, 1),
) -> None:
    """Fetch and render a material by its Materials Project ID.

    Args:
        material_id: The Materials Project ID (e.g., "mp-1234").
        api_key: Materials Project API key. Falls back to MP_API_KEY env var.
        supercell: Tuple of (nx, ny, nz) for supercell expansion.

    Raises:
        ValueError: If no API key is provided or material is not found.
    """
    key = _resolve_api_key(api_key)

    with MPRester(key) as mpr:
        docs = mpr.materials.summary.search(material_ids=[material_id])

        if not docs:
            raise ValueError(f"Material {material_id} not found")

        materials = extract_materials(docs)

        # Get formula for display
        formula = docs[0].formula_pretty if docs[0].formula_pretty else material_id

        plotter = pv.Plotter()
        plotter.set_background("white")

        view_crystal(
            materials[0],
            mpdoc=docs[0],
            supercell=supercell,
            plotter=plotter,
            formula=formula,
        )
