#!/usr/bin/env python3
"""
AlexaMods Labs — static site generator.

Adding a new application: append an entry to data/apps.json following the
existing schema, then re-run this script. Every page listed in the brief
(detail, privacy policy, terms, support, FAQ, release notes) is generated
automatically for it, and it appears in every hub/index page too.
"""
import json, os, shutil
from jinja2 import Environment, FileSystemLoader

ROOT = os.path.dirname(os.path.abspath(__file__))
DIST = os.path.join(ROOT, "dist")
TEMPLATES = os.path.join(ROOT, "templates")

env = Environment(loader=FileSystemLoader(TEMPLATES), trim_blocks=True, lstrip_blocks=True)

with open(os.path.join(ROOT, "data", "apps.json")) as f:
    APPS = json.load(f)

HOME_FAQS = [
    {"q": "Is AlexaMods Labs the official developer of these apps on Google Play?",
     "a": "Yes. This site is the official developer website linked from AlexaMods Labs' Google Play Console listing for every application in the catalog."},
    {"q": "Do your apps require an account or sign-in?",
     "a": "No. All AlexaMods Labs applications are designed to work without requiring account creation."},
    {"q": "How do I report a bug or request a feature?",
     "a": "Use the Report a Bug or Request a Feature button on any app's page, or the general Contact form, which reaches support@alexamodslabs.in directly."},
    {"q": "Are your apps free to use?",
     "a": "Yes, all current AlexaMods Labs applications are free to download, with some offering optional upgrades described in their individual Google Play listings."},
    {"q": "How quickly do you respond to support requests?",
     "a": "Our team monitors support@alexamodslabs.in 24×7 and typically replies within one to two business days."},
]

GLOBAL_FAQS = HOME_FAQS + [
    {"q": "Where can I find the Privacy Policy for a specific app?",
     "a": "Visit the Privacy Center, or go directly to that app's page and follow the Privacy Policy link in its legal section."},
    {"q": "Will new AlexaMods Labs apps appear on this site automatically?",
     "a": "Yes. Every new release is added to the Apps hub along with its own detail, privacy, terms, support, FAQ, and release notes pages, following the same structure as every existing app."},
]

NEWS = [
    {"title": "CineNest 6.1 adds a resizable floating window", "date": "July 15, 2026", "body": "The latest CineNest update lets you resize the floating playback window freely and improves subtitle track detection for MKV files.", "app_slug": "cinenest"},
    {"title": "FileNest 3.7 brings built-in ZIP support", "date": "July 8, 2026", "body": "FileNest can now create and extract ZIP archives directly, alongside a redesigned storage breakdown chart.", "app_slug": "filenest"},
    {"title": "GalleryNest adds biometric vault unlock", "date": "July 12, 2026", "body": "The private vault in GalleryNest now supports fingerprint and face unlock in addition to PIN protection.", "app_slug": "gallerynest"},
    {"title": "AlexaMods Labs crosses 10 published applications", "date": "June 1, 2026", "body": "With the addition of Force 5G NR and GPS Speedometer Live to active development, our catalog now spans utilities, productivity, and entertainment categories.", "app_slug": None},
]

SITE = "https://alexamodslabs.in"

def write(path, html):
    full = os.path.join(DIST, path.lstrip("/"))
    os.makedirs(os.path.dirname(full), exist_ok=True)
    with open(full, "w", encoding="utf-8") as f:
        f.write(html)

def render(template_name, canonical, meta_title, meta_description, **ctx):
    tpl = env.get_template(template_name)
    html = tpl.render(
        apps=APPS, canonical=canonical, meta_title=meta_title,
        meta_description=meta_description, **ctx
    )
    write(canonical.rstrip("/") + "/index.html" if canonical != "/" else "/index.html", html)

def related_apps(app, n=3):
    others = [a for a in APPS if a["slug"] != app["slug"]]
    return others[:n]

def main():
    if os.path.exists(DIST):
        shutil.rmtree(DIST)
    os.makedirs(DIST)

    # Static assets
    shutil.copytree(os.path.join(ROOT, "static", "css"), os.path.join(DIST, "css"))
    shutil.copytree(os.path.join(ROOT, "static", "js"), os.path.join(DIST, "js"))

    # Home
    render("home.html", "/", "AlexaMods Labs — Building Smarter Android Experiences",
           "AlexaMods Labs develops premium Android applications focused on performance, privacy, security, and reliability.",
           home_faqs=HOME_FAQS)

    # Apps hub
    render("apps_index.html", "/apps", "Apps — AlexaMods Labs",
           "Browse every Android application published by AlexaMods Labs.")

    # Hubs
    render("privacy_center.html", "/privacy", "Privacy Center — AlexaMods Labs",
           "Privacy policies for every AlexaMods Labs Android application.")
    render("terms_center.html", "/terms", "Terms Center — AlexaMods Labs",
           "Terms & Conditions for every AlexaMods Labs Android application.")
    render("support_center.html", "/support", "Support Center — AlexaMods Labs",
           "Technical support, bug reports, and feature requests for AlexaMods Labs applications.")
    render("about.html", "/about", "About — AlexaMods Labs",
           "AlexaMods Labs is an Android software studio focused on performance, privacy, and long-term support.")
    render("contact.html", "/contact", "Contact — AlexaMods Labs",
           "Contact AlexaMods Labs for support, bug reports, feature requests, or business inquiries.")
    render("faq_global.html", "/faq", "FAQ — AlexaMods Labs",
           "Frequently asked questions about AlexaMods Labs and its Android applications.", faqs=GLOBAL_FAQS)
    render("news.html", "/news", "News & Updates — AlexaMods Labs",
           "Product news and release highlights from AlexaMods Labs.", news=NEWS)
    render("release_notes_center.html", "/release-notes", "Release Notes — AlexaMods Labs",
           "Version history for every AlexaMods Labs Android application.")

    # Per-app pages
    for app in APPS:
        base = f"/apps/{app['slug']}"
        render("app_detail.html", base, f"{app['full_name']} — AlexaMods Labs",
               app["short_description"], app=app, related=related_apps(app))
        render("app_privacy.html", f"{base}/privacy-policy", f"{app['full_name']} Privacy Policy — AlexaMods Labs",
               f"Privacy Policy for {app['full_name']}, published by AlexaMods Labs.", app=app)
        render("app_terms.html", f"{base}/terms-and-conditions", f"{app['full_name']} Terms & Conditions — AlexaMods Labs",
               f"Terms & Conditions for {app['full_name']}, published by AlexaMods Labs.", app=app)
        render("app_support.html", f"{base}/support", f"{app['full_name']} Support — AlexaMods Labs",
               f"Get help with {app['full_name']}: troubleshooting, bug reports, and contact options.", app=app)
        render("app_faq.html", f"{base}/faq", f"{app['full_name']} FAQ — AlexaMods Labs",
               f"Frequently asked questions about {app['full_name']}.", app=app)
        render("app_release_notes.html", f"{base}/release-notes", f"{app['full_name']} Release Notes — AlexaMods Labs",
               f"Version history and release notes for {app['full_name']}.", app=app)

    # sitemap.xml
    urls = ["/", "/apps/", "/privacy/", "/terms/", "/support/", "/about/", "/contact/", "/faq/", "/news/", "/release-notes/"]
    for app in APPS:
        base = f"/apps/{app['slug']}/"
        urls += [base, base + "privacy-policy/", base + "terms-and-conditions/", base + "support/", base + "faq/", base + "release-notes/"]
    sitemap = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
    for u in urls:
        sitemap.append(f"  <url><loc>{SITE}{u}</loc></url>")
    sitemap.append("</urlset>")
    write("/sitemap.xml", "\n".join(sitemap))

    # robots.txt
    write("/robots.txt", f"User-agent: *\nAllow: /\nSitemap: {SITE}/sitemap.xml\n")

    total_pages = 10 + len(APPS) * 6
    print(f"Built {total_pages} pages + sitemap.xml + robots.txt into {DIST}")

if __name__ == "__main__":
    main()
