"""Hello World — minimal AliothPress plugin.

Demonstrates every integration point of the plugin API:
  * register(ctx)          — entry point, called once at startup
  * migrate(ctx)           — optional, idempotent, runs before register()
  * ctx.register_blueprint — own routes (admin or public)
  * ctx.register_admin_nav — a sidebar entry in the "Plugins" section
  * ctx.register_i18n_dir  — own translations (admin + public strings)
  * ctx.settings_get/set   — namespaced settings (stored as
                             plugin_hello_world_<key> in the settings table)
  * ctx.db                 — own SQLAlchemy models (tables are created
                             automatically after plugin load)

Delete this folder freely — it exists only as a template to copy.
"""

import os
from datetime import datetime, timezone

from flask import Blueprint, render_template_string, request, redirect, url_for
from flask_login import login_required, current_user

PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))

# Filled in register() so the model class can reference the live db object.
GreetingModel = None


def migrate(ctx):
    """Optional. Runs at every startup before register(). Keep idempotent.

    Table creation is handled automatically by db.create_all() after all
    plugins load, so this hook is only needed for column-level changes in
    later versions of your plugin (ALTER TABLE etc.), core-migrate style.
    """
    pass


def register(ctx):
    global GreetingModel
    db = ctx.db

    # ── Own model → own table (created automatically) ──────────────────
    class HelloGreeting(db.Model):
        __tablename__ = 'plugin_hello_world_greetings'   # prefix your tables!
        id = db.Column(db.Integer, primary_key=True)
        text = db.Column(db.String(200))
        created_at = db.Column(db.DateTime,
                               default=lambda: datetime.now(timezone.utc))

    GreetingModel = HelloGreeting

    # ── Translations (admin i18n/<lang>.json + optional public.json) ───
    ctx.register_i18n_dir(os.path.join(PLUGIN_DIR, 'i18n'))

    # ── Routes via a Blueprint ──────────────────────────────────────────
    bp = Blueprint('hello_world', __name__, url_prefix='/admin/hello-world')

    PAGE = """
    {% extends 'admin/base.html' %}
    {% block title %}{{ t('hello_world.title') }}{% endblock %}
    {% block content %}
    <div class="page-header">
        <h2>👋 {{ t('hello_world.title') }}</h2>
        <p>{{ t('hello_world.subtitle') }}</p>
    </div>
    <div class="settings-section">
        <p>{{ t('hello_world.counter', count=count) }}</p>
        <form method="POST" action="{{ url_for('hello_world.add') }}">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit" class="btn btn-primary">{{ t('hello_world.add_btn') }}</button>
        </form>
    </div>
    {% endblock %}
    """

    @bp.route('/')
    @login_required
    def index():
        count = GreetingModel.query.count()
        return render_template_string(PAGE, count=count)

    @bp.route('/add', methods=['POST'])
    @login_required
    def add():
        db.session.add(GreetingModel(
            text=f'Hello from {current_user.get_display_name()}'))
        db.session.commit()
        # Namespaced setting example (plugin_hello_world_last_greeting_by)
        ctx.settings_set('last_greeting_by', current_user.get_display_name())
        return redirect(url_for('hello_world.index'))

    ctx.register_blueprint(bp)

    # ── Sidebar entry (appears in the "Plugins" section for all admins) ─
    ctx.register_admin_nav('hello_world.nav_label', 'hello_world.index',
                           icon='👋')
