File size: 7,008 Bytes
71b378e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""
Character Export Tab for D'n'D Campaign Manager
"""

import gradio as gr
from typing import Tuple
import traceback
from src.agents.character_agent import CharacterAgent
from src.ui.components.dropdown_manager import DropdownManager
from src.utils.character_sheet_exporter import CharacterSheetExporter


class CharacterExportTab:
    """Export Character Sheet tab for exporting characters to various formats"""

    def __init__(self, character_agent: CharacterAgent, dropdown_manager: DropdownManager):
        self.character_agent = character_agent
        self.dropdown_manager = dropdown_manager
        self.exporter = CharacterSheetExporter()

    def export_character_sheet_ui(
        self,
        character_id: str,
        export_format: str = "markdown"
    ) -> str:
        """
        Export character sheet to file

        Returns:
            Status message with file path
        """
        try:
            if not character_id.strip():
                return "❌ Error: Please provide a character ID"

            # Load character
            character = self.character_agent.load_character(character_id)
            if not character:
                return f"❌ Character not found: {character_id}"

            # Export to selected format
            file_path = self.exporter.save_export(character, format=export_format)

            return f"""βœ… Character sheet exported successfully!

**Character:** {character.name}
**Format:** {export_format.upper()}
**File:** {file_path}

You can find the exported file in the data/exports/ directory."""

        except Exception as e:
            return f"❌ Error exporting character sheet:\n\n{str(e)}\n\n{traceback.format_exc()}"

    def preview_export_ui(
        self,
        character_id: str,
        export_format: str = "markdown"
    ) -> Tuple[str, str]:
        """
        Preview character sheet export without saving

        Returns:
            Tuple of (preview_content, status_message)
        """
        try:
            if not character_id.strip():
                return "", "❌ Error: Please provide a character ID"

            # Load character
            character = self.character_agent.load_character(character_id)
            if not character:
                return "", f"❌ Character not found: {character_id}"

            # Generate preview based on format
            if export_format == "markdown":
                preview = self.exporter.export_to_markdown(character)
            elif export_format == "json":
                preview = f"```json\n{self.exporter.export_to_json(character)}\n```"
            elif export_format == "html":
                preview = f"```html\n{self.exporter.export_to_html(character)}\n```"
            else:
                return "", f"❌ Unknown format: {export_format}"

            status = f"βœ… Preview generated for {character.name}"
            return preview, status

        except Exception as e:
            return "", f"❌ Error generating preview:\n\n{str(e)}\n\n{traceback.format_exc()}"

    def create(self) -> gr.Dropdown:
        """Create and return the Export Character Sheet tab component"""
        with gr.Tab("Export Character Sheet"):
            gr.Markdown("""
            ### πŸ“„ Export Character Sheets
            Export your characters to formatted character sheets in multiple formats!
            """)

            with gr.Row():
                with gr.Column():
                    export_char_refresh_btn = gr.Button("πŸ”„ Refresh Character List", variant="secondary")

                    export_character_dropdown = gr.Dropdown(
                        choices=[],
                        label="Select Character",
                        info="Choose a character to export (type to search)",
                        allow_custom_value=False,
                        interactive=True
                    )

                    export_format = gr.Radio(
                        choices=["markdown", "json", "html"],
                        label="Export Format",
                        value="markdown",
                        info="Choose the format for your character sheet"
                    )

                    with gr.Row():
                        preview_btn = gr.Button("πŸ‘οΈ Preview", variant="secondary")
                        export_btn = gr.Button("πŸ’Ύ Export to File", variant="primary")

                    export_status = gr.Textbox(
                        label="Status",
                        lines=6
                    )

                with gr.Column():
                    preview_output = gr.Markdown(
                        label="Preview",
                        value="Character sheet preview will appear here..."
                    )

            gr.Markdown("""
            ### Format Descriptions

            **Markdown (.md)**
            - Clean, readable text format with tables
            - Perfect for sharing in Discord, GitHub, or note apps
            - Includes all character stats, features, and background
            - Easy to read and edit

            **JSON (.json)**
            - Structured data format
            - Perfect for importing into other tools or programs
            - Contains all character data in a machine-readable format
            - Great for backup or data transfer

            **HTML (.html)**
            - Styled character sheet that can be opened in a browser
            - Print-ready format (mimics official D&D character sheet)
            - Beautiful parchment styling with maroon borders
            - Can be converted to PDF using browser's print function

            All exports are saved to the `data/exports/` directory.
            """)

            # Refresh export character dropdown
            export_char_refresh_btn.click(
                fn=self.dropdown_manager.refresh_character_dropdown,
                inputs=[],
                outputs=[export_character_dropdown]
            )

            # Preview action - convert dropdown label to ID
            def preview_from_dropdown(label, format):
                char_id = self.dropdown_manager.get_character_id_from_label(label)
                return self.preview_export_ui(char_id, format)

            preview_btn.click(
                fn=preview_from_dropdown,
                inputs=[export_character_dropdown, export_format],
                outputs=[preview_output, export_status]
            )

            # Export action - convert dropdown label to ID
            def export_from_dropdown(label, format):
                char_id = self.dropdown_manager.get_character_id_from_label(label)
                return self.export_character_sheet_ui(char_id, format)

            export_btn.click(
                fn=export_from_dropdown,
                inputs=[export_character_dropdown, export_format],
                outputs=[export_status]
            )

        # Return the dropdown for auto-population
        return export_character_dropdown