"""Solution for the MCP authorization practice."""
import re


def visible_rows(rows: list[dict], is_owner: bool, forced: bool, tenant: str | None) -> list[dict]:
    if is_owner and not forced:
        return rows
    if tenant is None:
        return []
    return [r for r in rows if r["tenant_id"] == tenant]


def insert_allowed(row_tenant: str, tenant: str | None) -> bool:
    return tenant is not None and row_tenant == tenant


def parse_challenge(www_authenticate: str) -> dict:
    return dict(re.findall(r'(\w+)="([^"]*)"', www_authenticate or ""))


def next_step(status: int, www_authenticate: str = "") -> str:
    params = parse_challenge(www_authenticate)
    if status == 401:
        return "get a new token" if params.get("error") == "invalid_token" else "sign in"
    if status == 403 and params.get("error") == "insufficient_scope":
        return f"ask for {params.get('scope', '')}"
    return "ok" if 200 <= status < 300 else "fail"
