import gradio as gr
import sys
from pathlib import Path
from typing import List
sys.path.append(str(Path(__file__).resolve().parent.parent))
from global_var import get_prompt_store
from schema.prompt import promptTempleta
def prompt_manage_page():
    def get_prompts() -> List[List[str]]:
        selected_row = None
        try:
            db = get_prompt_store()
            prompts = db.all()
            return [
                [p["id"], p["name"], p["description"], p["content"]]
                for p in prompts
            ]
        except Exception as e:
            raise gr.Error(f"获取提示词失败: {str(e)}")

    def add_prompt(name, description, content):
        try:
            db = get_prompt_store()
            new_prompt = promptTempleta(
                name=name if name else "",
                description=description if description else "",
                content=content if content else ""
            )
            prompt_id = db.insert(new_prompt.model_dump())
            # 更新ID
            db.update({"id": prompt_id}, doc_ids=[prompt_id])
            return get_prompts(), "", "", ""  # 返回清空后的输入框值
        except Exception as e:
            raise gr.Error(f"添加失败: {str(e)}")

    def edit_prompt():
        global selected_row
        if not selected_row:
            raise gr.Error("请先选择要编辑的行")
        try:
            db = get_prompt_store()
            db.update({
                "name": selected_row[1] if selected_row[1] else "",
                "description": selected_row[2] if selected_row[2] else "",
                "content": selected_row[3] if selected_row[3] else ""
            }, doc_ids=[selected_row[0]])
            return get_prompts()
        except Exception as e:
            raise gr.Error(f"编辑失败: {str(e)}")

    def delete_prompt():
        global selected_row
        if not selected_row:
            raise gr.Error("请先选择要删除的行")
        try:
            db = get_prompt_store()
            db.remove(doc_ids=[selected_row[0]])
            return get_prompts()
        except Exception as e:
            raise gr.Error(f"删除失败: {str(e)}")
        
    selected_row = None  # 保存当前选中行的全局变量
    
    def select_record(dataFrame ,evt: gr.SelectData):
        global selected_row
        selected_row = dataFrame.iloc[evt.index[0]].tolist()
        selected_row[0] = int(selected_row[0])
        print(selected_row)

    with gr.Blocks() as demo:
        gr.Markdown("## 提示词模板管理")

        with gr.Row():
            with gr.Column(scale=1):
                name_input = gr.Textbox(label="模板名称")
                description_input = gr.Textbox(label="模板描述")
                content_input = gr.Textbox(label="模板内容", lines=10)
                add_button = gr.Button("添加新模板", variant="primary")

            with gr.Column(scale=3):
                prompt_table = gr.DataFrame(
                    headers=["id", "名称", "描述", "内容"],
                    datatype=["number", "str", "str", "str"],
                    interactive=True,
                    value=get_prompts(),
                    wrap=True,
                    col_count=(4, "auto")
                )

                with gr.Row():
                    refresh_button = gr.Button("刷新数据", variant="secondary")
                    edit_button = gr.Button("编辑选中行", variant="primary")
                    delete_button = gr.Button("删除选中行", variant="stop")

        refresh_button.click(
            fn=get_prompts,
            outputs=[prompt_table],
            queue=False
        )

        add_button.click(
            fn=add_prompt,
            inputs=[name_input, description_input, content_input],
            outputs=[prompt_table, name_input, description_input, content_input]
        )

        prompt_table.select(fn=select_record, 
                              inputs=[prompt_table], 
                              outputs=[], 
                              show_progress="hidden")

        edit_button.click(
            fn=edit_prompt,
            inputs=[],
            outputs=[prompt_table]
        )

        delete_button.click(
            fn=delete_prompt,
            inputs=[],
            outputs=[prompt_table]
        )

        return demo
    

if __name__ == "__main__":
    demo = prompt_manage_page()
    demo.queue()
    demo.launch()