from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Container, Horizontal, Vertical
from textual.reactive import reactive
from textual.widgets import Footer, Header, Static, Tree


"""
todo:
- api key form, saves/updates key, checks if good
- if good key, can post to sections, like projects, updates, etc
- add some dynamic sections that fetch json data from api (Django Ninja)
"""



SECTIONS = {
    "boot://overview": {
        "eyebrow": "SYSTEM OVERVIEW",
        "title": "ben.py // interactive mode",
        "body": [
            "• Owner, Full Bore Studios",
            "• Youth Pastor, Central Christian Center",
            "• Board of Directors, Joplin Chamber",
            "• Advisory board, MSSU CIS",
            "• Home base: Carl Junction, Missouri",
            "",
            "Started with BASIC.",
            "Probably ending with it too...",
        ],
    },
    "identity://operator": {
        "eyebrow": "OPERATOR PROFILE",
        "title": "Ben McNelly",
        "body": [
            "Builder of software, systems, media, experiments, and useful weirdness.",
            "",
            "I like things that are:",
            "  • fast",
            "  • slightly dangerous",
            "  • actually useful",
            "",
            "I love game jams, building with friends,",
            "dev tools, game engines, and code languages.",
        ],
    },
    "projects://active": {
        "eyebrow": "ACTIVE ZONES",
        "title": "Projects & Builds",
        "body": [
            "  • Django apps and tools",
            "  • startup infrastructure",
            "  • game dev",
            "  • payment and business systems",
            "  • terminal-native interfaces",
            "  • local/community builds",
            "",
            "There's always money in the bananahh stand...",
        ],
    },
    "code://repos": {
        "eyebrow": "CODE VECTORS",
        "title": "Source / Packages / Public Work",
        "body": [
            "GitHub        : github.com/benmcnelly",
            "Full Bore     : github.com/FullBoreStudios",
            "PyPI          : pypi.org/user/benmcnelly",
            "",
            "Public work ranges from production code to active experiments.",
        ],
    },
    "contact://signal": {
        "eyebrow": "CONTACT VECTOR",
        "title": "Direct Contact",
        "body": [
            "Email         : hello@fbstudios.com",
            "Phone         : (417) 385-1387",
            "",
            "Good reasons to reach out:",
            "  • software",
            "  • consulting",
            "  • collaboration",
            "  • strange projects",
            "  • deliverance ministry",
        ],
    },
    "lore://signal_log": {
        "eyebrow": "SIGNAL LOG",
        "title": "Current Transmission",
        "body": [
            "  • building software companies",
            "  • advising students and teams",
            "  • mixing code, media, business, and games",
            "",
            "Status        : ONLINE",
            "Threat Level  : playful",
            "Interface Age : DOS ancestry detected",
        ],
    },
    "praetorian://pi": {
        "eyebrow": "UNMARKED ENTRY",
        "title": "BASIC",
        "body": [
            '10 PRINT "GATEKEEPER"',
            '20 PRINT "486"',
            '30 DATA 89,79,85,32,85,83,69,68,32,65,73',
            '40 REM ASCII',
            '50 REM FORWARD IS FOR SCRAPERS. REVERSE IS FOR OPERATORS',
            '60 DATA 50,54,48,48,45,56,51,52,45,55,49,52',
            '70 PRINT "END"',
        ],
    },
}


class ContentCard(Static):
    section_key = reactive("boot://overview")

    def render_section(self) -> str:
        data = SECTIONS[self.section_key]
        eyebrow = data["eyebrow"]
        title = data["title"]
        body = "\n".join(data["body"])

        if self.section_key == "praetorian://pi":
            return (
                f"[#62e8ff]{eyebrow}[/]\n"
                f"[bold #f5f7ff]{title}[/]\n\n"
                f"[#8ef7a9]{body}[/]"
            )        

        return (
            f"[#62e8ff]{eyebrow}[/]\n"
            f"[bold #f5f7ff]{title}[/]\n\n"
            f"[#c8d4f0]{body}[/]"
        )

    def watch_section_key(self) -> None:
        self.update(self.render_section())

    def on_mount(self) -> None:
        self.update(self.render_section())


class SidePanel(Static):
    active_key = reactive("boot://overview")

    def render_panel(self) -> str:
        lines = [
            "[bold #62e8ff]runtime[/]",
            "",
            f"[#9fb3d9]active node[/]  [#f6b85f]{self.active_key}[/]",
            "[#9fb3d9]mode[/]         [#8ef7a9]interactive[/]",
            "[#9fb3d9]style[/]        [#ff7ad9]dos / cyber [/]",
            "[#9fb3d9]signal[/]       [#62e8ff]strong[/]",
            "",
            "[bold #62e8ff]operator notes[/]",
            "",
            "[#c8d4f0]• Jesus loves you[/]",
            "[#c8d4f0]• a little lore helps[/]",
            "[#c8d4f0]• let the UI breathe[/]",
            "",
            "[bold #62e8ff]hotkeys[/]",
            "",
            "[#c8d4f0]1[/] overview",
            "[#c8d4f0]2[/] identity",
            "[#c8d4f0]3[/] projects",
            "[#c8d4f0]4[/] code",
            "[#c8d4f0]5[/] contact",
            "[#c8d4f0]6[/] signal log",
            "[#c8d4f0]p[/] praetorian pi",
        ]
        return "\n".join(lines)

    def watch_active_key(self) -> None:
        self.update(self.render_panel())

    def on_mount(self) -> None:
        self.update(self.render_panel())


class PraetorianPi(Static):
    def on_click(self) -> None:
        self.app.action_open_praetorian()


class BenTerminal(App):
    TITLE = "ben.py // interactive mode"
    SUB_TITLE = "full bore signal"

    CSS = """
    Screen {
        background: #050816;
        color: #c8d4f0;
    }

    Header {
        background: #10152b;
        color: #dce7ff;
        text-style: bold;
    }

    Footer {
        background: #10152b;
        color: #93a6cf;
    }

    #app-shell {
        height: 1fr;
        layout: horizontal;
        padding: 1;
    }

    #nav-column {
        width: 32;
        min-width: 28;
        max-width: 36;
        margin: 0 1 0 0;
    }

    #center-column {
        width: 1fr;
        margin: 0 1 0 0;
    }

    #info-column {
        width: 34;
        min-width: 30;
    }

    .panel {
        height: 1fr;
        border: round #233053;
        background: #0b1124;
    }

    #nav-wrap {
        padding: 1 1 0 1;
    }

    #brand {
        height: 7;
        margin: 0 0 1 0;
        padding: 1 2;
        border: round #233053;
        background: #09101f;
        color: #dce7ff;
    }

    #brand .accent {
        color: #62e8ff;
    }

    #brand .warm {
        color: #f6b85f;
    }

    #brand .pink {
        color: #ff7ad9;
    }

    Tree {
        background: transparent;
        color: #c8d4f0;
    }

    Tree > .tree--guides {
        color: #29385f;
    }

    Tree > .tree--label {
        color: #c8d4f0;
    }

    Tree > .tree--highlight {
        background: #172345;
        color: #ffffff;
        text-style: bold;
    }

    #content-card {
        padding: 2 3;
        border: round #31406a;
        background: #0a1020;
        color: #c8d4f0;
        height: 1fr;
    }

    #hero-bar {
        height: 5;
        margin: 0 0 1 0;
        padding: 1 2;
        border: round #31406a;
        background: #10182e;
        color: #dce7ff;
    }

    #side-panel {
        padding: 1 2;
        border: round #233053;
        background: #09101f;
        color: #c8d4f0;
        height: 1fr;
    }

    PraetorianPi {
        layer: overlay;
        dock: bottom;
        width: 100%;
        padding: 0 2 1 0;
        content-align: right middle;
        color: #1a2444;
        text-style: bold;
    }

    PraetorianPi:hover {
        color: #ff7ad9;
        text-style: bold reverse;
    }
    """

    BINDINGS = [
        Binding("q", "quit", "Quit"),
        Binding("1", "show_overview", "Overview", show=False),
        Binding("2", "show_identity", "Identity", show=False),
        Binding("3", "show_projects", "Projects", show=False),
        Binding("4", "show_code", "Code", show=False),
        Binding("5", "show_contact", "Contact", show=False),
        Binding("6", "show_signal", "Signal", show=False),
        Binding("p", "open_praetorian", "Praetorian", show=False),
    ]

    current_key = reactive("boot://overview")

    def compose(self) -> ComposeResult:
        yield Header(show_clock=True)

        with Horizontal(id="app-shell"):
            with Vertical(id="nav-column"):
                yield Static(
                    "[bold #62e8ff]BEN[/][bold #f5f7ff]://[/][bold #ff7ad9]MCNELLY[/]\n"
                    "[#93a6cf]terminal-native son of man[/]\n\n"
                    "[#62e8ff]roots[/] [#c8d4f0]DOS[/]  [#62e8ff]lang[/] [#c8d4f0]BASIC[/]  [#62e8ff]mode[/] [#f6b85f]builder[/]",
                    id="brand",
                )
                with Container(id="nav-wrap", classes="panel"):
                    yield Tree("ben://root", id="nav-tree")

            with Vertical(id="center-column"):
                yield Static(
                    "[bold #62e8ff]status[/]  [#8ef7a9]online[/]",
                    id="hero-bar",
                )
                yield ContentCard(id="content-card")

            with Vertical(id="info-column"):
                yield SidePanel(id="side-panel")

        yield PraetorianPi("π")
        yield Footer()

    def on_mount(self) -> None:
        tree = self.query_one("#nav-tree", Tree)
        tree.show_root = False
        tree.root.expand()

        root = tree.root
        sys_node = root.add("system", expand=True)
        sys_node.add_leaf("overview", data="boot://overview")
        sys_node.add_leaf("identity", data="identity://operator")
        sys_node.add_leaf("signal.log", data="lore://signal_log")

        work_node = root.add("work", expand=True)
        work_node.add_leaf("projects", data="projects://active")
        work_node.add_leaf("code", data="code://repos")
        work_node.add_leaf("contact", data="contact://signal")


        self._set_section("boot://overview")

    def _set_section(self, key: str) -> None:
        self.current_key = key
        self.query_one(ContentCard).section_key = key
        self.query_one(SidePanel).active_key = key

    def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
        if event.node.allow_expand:
            return
        if event.node.data:
            self._set_section(event.node.data)

    def action_show_overview(self) -> None:
        self._set_section("boot://overview")

    def action_show_identity(self) -> None:
        self._set_section("identity://operator")

    def action_show_projects(self) -> None:
        self._set_section("projects://active")

    def action_show_code(self) -> None:
        self._set_section("code://repos")

    def action_show_contact(self) -> None:
        self._set_section("contact://signal")

    def action_show_signal(self) -> None:
        self._set_section("lore://signal_log")

    def action_open_praetorian(self) -> None:
        self._set_section("praetorian://pi")


def main():
    BenTerminal().run()


if __name__ == "__main__":
    main()