# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/02_pingme_api.ipynb.

# %% auto 0
__all__ = ['app', 'Settings', 'read_main', 'send_webhook', 'send_webhook_test', 'webservice']

# %% ../nbs/02_pingme_api.ipynb 2
import json
import os
import re

import uvicorn
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel

from . import core
from .pingme_class import Card, PingMe
from pydantic_settings import BaseSettings

# %% ../nbs/02_pingme_api.ipynb 4
class Settings(BaseSettings):
    app_name: str = "PingMe"
    config_file: str = ""


if core.DEV_MODE:
    settings = Settings(config_file=f"{core.PROJECT_DIR}/config/config.env")
else:
    settings = Settings()

# %% ../nbs/02_pingme_api.ipynb 5
app = FastAPI()


@app.get("/")
async def read_main():
    # Using the default place as a information post
    return {"msg": "PingMe: please POST to /webhook or /email or /logfile}"}

# %% ../nbs/02_pingme_api.ipynb 7
from fastapi import HTTPException


@app.post("/webhook")
async def send_webhook(card: Card):
    try:
        notification = PingMe(card)
        print(notification.payload)
        response = notification.send_webhook()
    except Exception as e:
        raise HTTPException(status_code=404, detail=f"Error: {e}")
    return response

# %% ../nbs/02_pingme_api.ipynb 8
@app.get("/webhook_test")
async def send_webhook_test():
    try:
        card = Card.model_validate(
            {
                "name": "default",
                "context": {"title": "Test Title", "text": "Test Text"},
            }
        )
        notification = PingMe(
            card,
            config_file=settings.config_file,
        )
        response = notification.send_webhook()
    except Exception as e:
        raise HTTPException(status_code=404, detail=f"Error: {e}")
    return response

# %% ../nbs/02_pingme_api.ipynb 10
def webservice():
    uvicorn.run(app, port=5000, log_level="info")
