from __future__ import annotations


def render_python_snippet(intent: str) -> str:
    intent = (intent or "snippet").strip().replace("\n", " ")[:200]
    return f'''# -*- coding: utf-8 -*-
"""Intent: {intent}"""
import sys

def main() -> int:
    # TODO: implement
    return 0

if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as e:
        print(f"error: {{e}}", file=sys.stderr)
        raise SystemExit(1)
'''


def render_bash_snippet(intent: str) -> str:
    intent = (intent or "snippet").strip().replace("\n", " ")[:200]
    return f'''#!/usr/bin/env bash
set -euo pipefail
# Intent: {intent}

main() {{
  # TODO: implement
  :
}}

main "$@"
'''


def render_cmd_snippet(intent: str) -> str:
    intent = (intent or "snippet").strip().replace("\n", " ")[:200]
    return f'''@echo off
chcp 65001 >nul
setlocal EnableExtensions
REM Intent: {intent}

REM TODO: implement

endlocal
exit /b 0
'''


def render_ps1_snippet(intent: str) -> str:
    intent = (intent or "snippet").strip().replace("\n", " ")[:200]
    return f'''$ErrorActionPreference = "Stop"
# Intent: {intent}

function Main {{
    # TODO: implement
}}

try {{
    Main
}} catch {{
    Write-Error $_
    exit 1
}}
'''


def render(shell: str, intent: str) -> dict[str, object]:
    s = shell.strip().lower()
    if s in ("py", "python"):
        return {"ok": True, "shell": "py", "source": render_python_snippet(intent)}
    if s in ("bash", "sh"):
        return {"ok": True, "shell": "bash", "source": render_bash_snippet(intent)}
    if s == "cmd":
        return {"ok": True, "shell": "cmd", "source": render_cmd_snippet(intent)}
    if s in ("ps1", "powershell", "pwsh"):
        return {"ok": True, "shell": "ps1", "source": render_ps1_snippet(intent)}
    return {"ok": False, "error": f"unknown shell: {shell}"}
