import os
import json
import random
from flask import Blueprint, redirect, url_for, render_template, g, request, flash
from typing import cast

from app.utils.session_user import SessionUser
from app.services.appwrite_client import AppWriteClient
from app.services.appwrite_db import AppwriteTables, Env
from app.services.coc_api import CoCApi

char_bp = Blueprint("char", __name__, url_prefix="/char")

cocapi = CoCApi()


def get_current_user() -> SessionUser:
    return cast(SessionUser, g.current_user)


@char_bp.route("/create", methods=["GET", "POST"])
def create_char():
    if request.method == "POST":
        name = request.form.get("character_name")
        race_id = request.form.get("race_dropdown")
        profession_id = request.form.get("profession_dropdown")
        origin_story = request.form.get("origin_story")
        uuid = cocapi.create_char(name=name,origin_story=origin_story,race_id=race_id,profession_id=profession_id)
        redirect(url_for("main.dashboard"))

    ai_dumps_path = os.path.join("app","game_data","ai_dumps.json")
    with open(ai_dumps_path,"r") as f:
        data = json.load(f)

    origin_stories = data.get("origin_stories",[])
    if len(origin_stories) > 0:
        starter_text = random.choice(origin_stories)
    else:
        starter_text = "I was born in a small, secluded village on the edge of a vast and mysterious forest, where whispers of ancient magic still lingered in the air."

    template_data = {
        "starter_text":starter_text
    }
    
    return render_template("char/create_char.html", data=template_data)
    
