"""Canonical §1 (Quickstart, T1+T2) cell sequence shared by every notebook.

All cells are tier=1 (pure offline, no network). They exercise:
1. SDK version + import sanity
2. Local-mode Patter construction (Twilio carrier)
3. Cloud-mode stub (currently raises NotImplementedError — cloud coming soon)
4. Agent engine dispatch (Realtime / ConvAI / Pipeline)
"""

from __future__ import annotations


def _md(*lines: str) -> dict:
    return {"cell_type": "markdown", "metadata": {}, "source": list(lines)}


def _code(tag: str, source: str) -> dict:
    return {
        "cell_type": "code",
        "metadata": {"tags": [tag]},
        "source": source.splitlines(keepends=True),
        "execution_count": None,
        "outputs": [],
    }


def quickstart_cells_python() -> list[dict]:
    return [
        _md(
            "These cells run with **zero API keys** in <30 seconds. "
            "They exercise the public Patter API offline (no network, no carrier calls).\n"
        ),
        _code(
            "qs_version_check",
            "import sys\n"
            "import getpatter\n"
            "with _setup.cell('version_check', tier=1, env=env) as ok:\n"
            "    if ok:\n"
            "        print(f'getpatter {getpatter.__version__} on Python {sys.version.split()[0]}')\n"
            "        assert getpatter.__version__ >= env.patter_version, \\\n"
            "            f'installed {getpatter.__version__} < target {env.patter_version}'\n",
        ),
        _md(
            "### Local mode\n"
            "Construct a Patter instance with a Twilio carrier. No API key — runs entirely on your machine.\n"
        ),
        _code(
            "qs_local_mode",
            "from getpatter import Patter, Twilio\n"
            "with _setup.cell('local_mode', tier=1, env=env) as ok:\n"
            "    if ok:\n"
            "        p = Patter(\n"
            "            carrier=Twilio(\n"
            "                account_sid='ACtest00000000000000000000000000',\n"
            "                auth_token='test',\n"
            "            ),\n"
            "            phone_number='+15555550100',\n"
            "            webhook_url='https://example.com/webhook',\n"
            "        )\n"
            "        # Verify carrier is wired up via LocalConfig.\n"
            "        assert p._local_config.telephony_provider == 'twilio'\n"
            "        assert p._local_config.phone_number == '+15555550100'\n"
            "        print(f'provider={p._local_config.telephony_provider}  phone={p._local_config.phone_number}')\n",
        ),
        _md(
            "### Cloud mode (coming soon)\n"
            "When `api_key=` is supported, Patter cloud handles telephony. "
            "For now, the SDK raises `NotImplementedError` — this cell verifies the guard.\n"
        ),
        _code(
            "qs_cloud_mode",
            "from getpatter import Patter\n"
            "with _setup.cell('cloud_mode', tier=1, env=env) as ok:\n"
            "    if ok:\n"
            "        try:\n"
            "            Patter(api_key='pt_test_xxx')\n"
            "            raise AssertionError('expected NotImplementedError — cloud mode guard missing')\n"
            "        except NotImplementedError as exc:\n"
            "            print(f'cloud mode guard OK: {exc}')\n",
        ),
        _md(
            "### Three engine types\n"
            "An agent picks one of *OpenAI Realtime*, *ElevenLabs ConvAI*, or *Pipeline* "
            "(STT + LLM + TTS). The factory derives the engine from `engine=` / `stt=`/`tts=`.\n"
        ),
        _code(
            "qs_agent_engines",
            "from getpatter import Patter, Twilio, OpenAIRealtime, ElevenLabsConvAI\n"
            "with _setup.cell('agent_engines', tier=1, env=env) as ok:\n"
            "    if ok:\n"
            "        p = Patter(\n"
            "            carrier=Twilio(account_sid='ACtest00000000000000000000000000',\n"
            "                           auth_token='test'),\n"
            "            phone_number='+15555550100',\n"
            "            webhook_url='https://example.com/webhook',\n"
            "        )\n"
            "        rt = p.agent(system_prompt='hi', engine=OpenAIRealtime(api_key='sk-test'))\n"
            "        cv = p.agent(system_prompt='hi', engine=ElevenLabsConvAI(api_key='el-test', agent_id='a1'))\n"
            "        pl = p.agent(system_prompt='hi')  # default: OpenAI Realtime fallback\n"
            "        assert rt.provider == 'openai_realtime', rt.provider\n"
            "        assert cv.provider == 'elevenlabs_convai', cv.provider\n"
            "        assert pl.provider == 'openai_realtime', pl.provider\n"
            "        print(f'rt.provider={rt.provider}  cv.provider={cv.provider}  pl.provider={pl.provider}')\n",
        ),
    ]


def quickstart_cells_typescript() -> list[dict]:
    return [
        _md(
            "These cells run with **zero API keys** in <30 seconds. "
            "They exercise the public Patter API offline.\n"
        ),
        _code(
            "qs_version_check",
            'import { cell } from "./_setup.ts";\n'
            'import * as getpatter from "getpatter";\n'
            "await cell('version_check', { tier: 1, env }, () => {\n"
            "  const v = (getpatter as any).version ?? (getpatter as any).VERSION ?? 'unknown';\n"
            "  console.log(`getpatter ${v}`);\n"
            "});\n",
        ),
        _md("### Local mode\nConstruct a Patter instance with a Twilio carrier.\n"),
        _code(
            "qs_local_mode",
            'import { Patter, Twilio } from "getpatter";\n'
            "await cell('local_mode', { tier: 1, env }, () => {\n"
            "  const p = new Patter({\n"
            "    carrier: new Twilio({\n"
            "      accountSid: 'ACtest00000000000000000000000000',\n"
            "      authToken: 'test',\n"
            "    }),\n"
            "    phoneNumber: '+15555550100',\n"
            "    webhookUrl: 'https://example.com/webhook',\n"
            "  });\n"
            "  console.log('Patter local mode constructed OK');\n"
            "});\n",
        ),
        _md(
            "### Cloud mode (coming soon)\n"
            "When `apiKey` is supported, Patter cloud handles telephony. "
            "For now, the SDK throws — this cell verifies the guard.\n"
        ),
        _code(
            "qs_cloud_mode",
            'import { Patter } from "getpatter";\n'
            "await cell('cloud_mode', { tier: 1, env }, () => {\n"
            "  try {\n"
            "    new Patter({ apiKey: 'pt_test_xxx' } as any);\n"
            "    throw new Error('expected error — cloud mode guard missing');\n"
            "  } catch (e: any) {\n"
            "    if (e.message?.includes('Cloud') || e.message?.includes('cloud') || e.message?.includes('apiKey')) {\n"
            "      console.log(`cloud mode guard OK: ${e.message.slice(0, 80)}`);\n"
            "    } else { throw e; }\n"
            "  }\n"
            "});\n",
        ),
        _md(
            "### Three engine types\n"
            "An agent picks one of *OpenAI Realtime*, *ElevenLabs ConvAI*, or *Pipeline*.\n"
        ),
        _code(
            "qs_agent_engines",
            'import { Patter, Twilio, OpenAIRealtime, ElevenLabsConvAI } from "getpatter";\n'
            "await cell('agent_engines', { tier: 1, env }, () => {\n"
            "  const p = new Patter({\n"
            "    carrier: new Twilio({ accountSid: 'ACtest00000000000000000000000000', authToken: 'test' }),\n"
            "    phoneNumber: '+15555550100',\n"
            "    webhookUrl: 'https://example.com/webhook',\n"
            "  });\n"
            "  const rt = p.agent({ systemPrompt: 'hi', engine: new OpenAIRealtime({ apiKey: 'sk-test' }) });\n"
            "  const cv = p.agent({ systemPrompt: 'hi', engine: new ElevenLabsConvAI({ apiKey: 'el-test', agentId: 'a1' }) });\n"
            "  const pl = p.agent({ systemPrompt: 'hi' });\n"
            "  if (rt.provider !== 'openai_realtime') throw new Error(`expected openai_realtime, got ${rt.provider}`);\n"
            "  if (cv.provider !== 'elevenlabs_convai') throw new Error(`expected elevenlabs_convai, got ${cv.provider}`);\n"
            "  console.log(`rt=${rt.provider}  cv=${cv.provider}  pl=${pl.provider}`);\n"
            "});\n",
        ),
    ]
