#!/usr/bin/env python3
"""
setup-nomadnet-pages.py
Creates a working 3-page sample NomadNet µ-site you can browse, edit, and build on.

Usage:
    python3 setup-nomadnet-pages.py

Works on Linux, macOS, and Windows.
Pages are written in Micron — NomadNet's simple markup language.

After running this script:
  1. Start (or restart) your NomadNet node
  2. Visit your node's destination hash in Nomad NetBrowser
  3. You'll see a working 3-page site immediately
  4. Edit the .mu files in the pages directory to make it yours
"""

import os
import sys
import shutil
import datetime

# ── Pages directory by platform ───────────────────────────────────────────────

if sys.platform == "win32":
    NOMADNET_DIR = os.path.join(os.environ.get("APPDATA", ""), "nomadnetwork", "storage", "pages")
else:
    NOMADNET_DIR = os.path.join(os.path.expanduser("~"), ".nomadnetwork", "storage", "pages")

# ── Micron page content ───────────────────────────────────────────────────────
# Micron quick reference:
#   >Text         — Heading (use >> for sub-heading, >>> for smaller)
#   `!`Bold`!!`   — Bold text on / off
#   `_`Line`__`   — Underline on / off
#   `F9``Text`f`  — Colored text (0-255 or name: red, green, blue, cyan, etc.)
#   ---           — Horizontal rule
#   `[Label]=hash/page.mu` — Link to another page
#   Blank line    — Spacer

INDEX_MU = """\
>`F9`WELCOME TO MY NODE`f`

Hello, traveller. You found me on the `!`Nomad Network`!!` —
a decentralised mesh of pages and people running over Reticulum.

This page is hosted locally on my machine and served directly
to you over the mesh. No servers. No cloud. No middlemen.

---

>>`F14`About This Node`f`

This node is running `!`NomadNet`!!` connected via Reticulum.
It can be reached over TCP/IP, LoRa radio, or any other
Reticulum-compatible link — whatever path exists between us.

My LXMF address is the same as my node's destination hash.
You can message me directly from `!`Nomad NetBrowser`!!`.

---

>>`F14`Explore This Site`f`

`[About This Node]=`/page/about.mu`
`[Links & Resources]=`/page/links.mu`

---

>>`F8`Getting Started on the Mesh`f`

New to Nomad Network? The easiest way to browse is with
`!`Nomad NetBrowser`!!` — a free app that wraps the whole
network in a regular browser window.

`[Get Nomad NetBrowser at nodestar.net]=` https://nodestar.net

---

`F8`This site was generated by setup-nomadnet-pages.py`f`
`F8`Edit the .mu files to make it yours.`f`
"""

ABOUT_MU = """\
>`F9`About This Node`f`

`[← Back to Home]=`/page/index.mu`

---

>>`F14`Who Am I?`f`

`!`Edit this page to introduce yourself.`!!`

This is your space on the mesh. You can write anything here:
who you are, where you're located, what you're interested in,
what you're experimenting with, or why you got into Reticulum.

---

>>`F14`My Setup`f`

`!`Hardware:`!!`          Edit this with your actual setup
`!`Connection:`!!`        TCP backbone / LoRa / local mesh
`!`Location:`!!`          Your city or region
`!`Operator:`!!`          Your name or callsign

---

>>`F14`What I'm Working On`f`

Replace this with your current projects, experiments,
or anything you want to share with the mesh community.

---

>>`F14`Contact`f`

My LXMF address is the same as this node's destination hash.
Paste it into any compatible app to send me a message:

  `!`Sideband`!!` (Android/iOS)
  `!`MeshChat`!!`
  `!`Nomad NetBrowser`!!` → Messages tab

---

`[Links & Resources]=`/page/links.mu`
`[← Back to Home]=`/page/index.mu`
"""

LINKS_MU = """\
>`F9`Links & Resources`f`

`[← Back to Home]=`/page/index.mu`

---

>>`F14`Getting Started`f`

`!`Nomad NetBrowser`!!` — browse µ-pages in any web browser
  https://nodestar.net

`!`Reticulum Network Stack`!!` — the protocol that makes this possible
  https://reticulum.network

`!`rmap.world`!!` — interactive map of Reticulum backbone nodes
  https://rmap.world

`!`directory.rns.recipes`!!` — curated list of public entrypoints
  https://directory.rns.recipes

---

>>`F14`Node Star Directory`f`

List your node so others can find you:

  Submit at:  https://nodestar.net/node-submit
  Directory:  https://nodestar.net/directory

---

>>`F14`Compatible Apps`f`

`!`Sideband`!!` — LXMF messenger for Android and iOS
`!`MeshChat`!!` — Group messaging over Reticulum
`!`NomadNet`!!` — Terminal interface and node server
`!`Nomad NetBrowser`!!` — Web browser interface (this app)

All of these share the same LXMF address space.
You can message between any of them.

---

>>`F14`Starter Nodes to Visit`f`

Paste these hashes into the Nomad NetBrowser address bar:

`!`Node Star`!!`
9a5548134799cfb6e9f60decc8708bc1

`!`BetweenTheBorders`!!`
f8ac9c41b857ddf13a9151cec211079b

---

>>`F14`Learn More`f`

`!`Reticulum Manual`!!`
  https://reticulum.network/manual

`!`NomadNet on GitHub`!!`
  https://github.com/markqvist/NomadNet

`!`Nomad NetBrowser on Codeberg`!!`
  https://codeberg.org/node-star/nomad-netbrowser

---

`[About This Node]=`/page/about.mu`
`[← Back to Home]=`/page/index.mu`
"""

BANNER = """
╔══════════════════════════════════════════════════════╗
║     NomadNet Sample Site Setup — Node Star           ║
║     https://nodestar.net                             ║
╚══════════════════════════════════════════════════════╝
"""

# ── Helpers ───────────────────────────────────────────────────────────────────

def yn(msg, default="y"):
    choices = "Y/n" if default == "y" else "y/N"
    val = input(f"{msg} [{choices}]: ").strip().lower()
    if not val:
        return default == "y"
    return val.startswith("y")

# ── Main ──────────────────────────────────────────────────────────────────────

PAGES = {
    "index.mu": INDEX_MU,
    "about.mu": ABOUT_MU,
    "links.mu": LINKS_MU,
}

def main():
    print(BANNER)
    print(f"This script will create a 3-page sample NomadNet µ-site at:\n")
    print(f"  {NOMADNET_DIR}\n")
    print("Pages created:")
    for name in PAGES:
        print(f"  • {name}")
    print()

    # ── Check for existing pages ───────────────────────────────────────────────
    existing = [p for p in PAGES if os.path.exists(os.path.join(NOMADNET_DIR, p))]
    if existing:
        print("The following pages already exist:")
        for p in existing:
            print(f"  ! {p}")
        print()
        if not yn("Overwrite them?", default="n"):
            print("\nNo changes made. Exiting.")
            sys.exit(0)
        # Back up any existing pages
        ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        for p in existing:
            src = os.path.join(NOMADNET_DIR, p)
            dst = src + f".backup_{ts}"
            shutil.copy2(src, dst)
            print(f"  ✓ Backed up {p} → {os.path.basename(dst)}")
        print()

    # ── Write pages ────────────────────────────────────────────────────────────
    os.makedirs(NOMADNET_DIR, exist_ok=True)

    for filename, content in PAGES.items():
        path = os.path.join(NOMADNET_DIR, filename)
        with open(path, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"  ✓ Written: {filename}")

    print()
    print("═" * 54)
    print("  Sample site created!")
    print("═" * 54)
    print()
    print(f"  Pages location:")
    print(f"  {NOMADNET_DIR}")
    print()
    print("  Next steps:")
    print("  1. Start (or restart) your NomadNet node")
    print("  2. Your destination hash will be shown in the NomadNet")
    print("     console output — copy it")
    print("  3. Paste that hash into Nomad NetBrowser's address bar")
    print("  4. You'll see your working 3-page site immediately")
    print()
    print("  To customise your site:")
    print("  • Edit index.mu  — your home page")
    print("  • Edit about.mu  — introduce yourself")
    print("  • Edit links.mu  — your curated link list")
    print()
    print("  Micron quick reference:")
    print("  >Heading        — heading")
    print("  >>Sub-heading   — smaller heading")
    print("  `!`Bold`!!`     — bold text")
    print("  `_`Line`__`     — underlined text")
    print("  `Fcolor`Text`f` — colored text (red, green, cyan, 0-255)")
    print("  ---             — horizontal rule")
    print("  `[Label]=hash/page.mu` — link to another page")
    print()
    print("  Get listed in the Node Star directory:")
    print("  → https://nodestar.net/node-submit")
    print()

if __name__ == "__main__":
    main()
