from __future__ import annotations
import json
from typing import Iterator, Tuple
import requests

def iter_frames(resp: requests.Response) -> Iterator[Tuple[str, str]]:
    """
    自动探测并输出帧：
    - SSE:  ("json", payload_str) or ("done","")
    - JSONL:("json", line)
    - JSON: ("json", whole_json_str) 只会产出一次
    """
    ctype = (resp.headers.get("Content-Type") or "").lower()

    # 1) SSE
    if "text/event-stream" in ctype:
        buff = ""
        for line in resp.iter_lines(decode_unicode=True):
            if line is None:
                continue
            line = line.strip()
            if not line:
                continue
            if not line.startswith("data:"):
                continue
            data = line[5:].strip()
            if data == "[DONE]":
                yield ("done", "")
                return
            yield ("json", data)
        yield ("done", "")
        return

    # 2) 可能是 JSONL
    if "application/x-ndjson" in ctype or "jsonl" in ctype:
        for line in resp.iter_lines(decode_unicode=True):
            if not line:
                continue
            yield ("json", line)
        yield ("done", "")
        return

    # 3) 兜底：尝试按行当 JSONL；如果只有一大段 JSON，就当单帧
    lines = []
    for line in resp.iter_lines(decode_unicode=True):
        if line:
            lines.append(line)
    if not lines:
        yield ("done", "")
        return
    if len(lines) == 1:
        yield ("json", lines[0])
        yield ("done", "")
        return
    # 多行：尽量逐行 json
    for line in lines:
        yield ("json", line)
    yield ("done", "")
