"""Generate the client-facing monthly update PDF."""
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, ListFlowable, ListItem, PageBreak,
)
from reportlab.lib.enums import TA_LEFT

OUTPUT = "/home/user/VYA-frontend/VYA_Platform_Updates_Past_Month.pdf"

BRAND = colors.HexColor("#EF4136")
DARK = colors.HexColor("#1F2937")
SUBTLE = colors.HexColor("#6B7280")

styles = getSampleStyleSheet()

title_style = ParagraphStyle(
    "Title", parent=styles["Title"], fontSize=24, leading=28,
    textColor=DARK, spaceAfter=6, alignment=TA_LEFT,
)
subtitle_style = ParagraphStyle(
    "Subtitle", parent=styles["Normal"], fontSize=11, leading=14,
    textColor=SUBTLE, spaceAfter=20,
)
h1_style = ParagraphStyle(
    "H1", parent=styles["Heading1"], fontSize=16, leading=20,
    textColor=BRAND, spaceBefore=18, spaceAfter=6,
)
h2_style = ParagraphStyle(
    "H2", parent=styles["Heading2"], fontSize=13, leading=16,
    textColor=DARK, spaceBefore=12, spaceAfter=4,
)
body_style = ParagraphStyle(
    "Body", parent=styles["Normal"], fontSize=10.5, leading=15,
    textColor=DARK, spaceAfter=2,
)


def bullets(items):
    return ListFlowable(
        [ListItem(Paragraph(t, body_style), leftIndent=12, bulletColor=BRAND)
         for t in items],
        bulletType="bullet", bulletFontSize=8, leftIndent=14,
    )


story = []

# Header
story.append(Paragraph("VYA Platform Updates", title_style))
story.append(Paragraph("Summary of improvements delivered over the past month", subtitle_style))

# =======================================================================
# CLIENT APP
# =======================================================================
story.append(Paragraph("Client App", h1_style))

story.append(Paragraph("Smoother Sign-In &amp; Session Experience", h2_style))
story.append(bullets([
    "Fixed an issue where customers could get \u201cstuck\u201d after their session expired and were unable to reach the login page \u2014 the app now cleanly recovers and lets them sign back in.",
    "Added a <b>seamless background session refresh</b> so shoppers stay logged in longer without being interrupted mid-browsing or mid-checkout.",
    "Proactive token refresh kicks in before the session expires, so long browsing sessions don\u2019t end with an unexpected logout.",
    "Eliminated confusing \u201cunauthorized\u201d error pop-ups that could appear during logout or while browsing public pages as a guest.",
    "When an admin invalidates a session (e.g. after a security event or password change), affected users are now cleanly signed out instead of seeing broken behavior.",
    "Customers are no longer bounced to the \u201cunauthorized\u201d page for routine permission checks, avoiding unexpected interruptions.",
    "The app now listens for server-side session updates and applies them immediately, keeping customer sessions in sync with the backend.",
]))

story.append(Paragraph("Chat &amp; Push Notifications", h2_style))
story.append(bullets([
    "Chat unread-count and notification checks no longer fire for <b>logged-out visitors</b> \u2014 guests get a faster, quieter load and the server receives fewer unnecessary requests.",
    "Cleaned up how push/chat calls behave around login and logout transitions so counts stay accurate and don\u2019t flash stale values.",
]))

story.append(Paragraph("Submissions Experience", h2_style))
story.append(bullets([
    "Added a <b>submission status badge</b> directly on product cards so customers can see at a glance where each of their entries stands (pending, approved, etc.) without needing to click in.",
    "Introduced <b>status filter chips</b> on the submissions view \u2014 customers can quickly filter by state instead of scrolling through the full list.",
    "Filtering now happens instantly on the customer\u2019s device, so switching between statuses feels snappy with no extra loading time.",
]))

story.append(Paragraph("Notifications", h2_style))
story.append(bullets([
    "Fixed notifications being <b>cut off mid-sentence</b> \u2014 customers can now read the full message text in the notification list.",
    "Improved typography and spacing so longer messages display cleanly in the dropdown.",
]))

story.append(Paragraph("Maps", h2_style))
story.append(bullets([
    "Upgraded to Google\u2019s newer <b>advanced marker system</b> so map pins render reliably and future Google Maps updates won\u2019t break the experience.",
    "Improved city lookup to use Google\u2019s official client library \u2014 faster and more accurate when customers search or pin their location.",
]))

story.append(Paragraph("Performance &amp; Stability", h2_style))
story.append(bullets([
    "Adjusted caching so customers always receive the <b>freshest page content</b> while still benefiting from fast loads on repeat visits.",
    "Eliminated a couple of errors that appeared when the app first started \u2014 a cleaner, more reliable boot for every visitor.",
]))

story.append(Paragraph("Data Reliability", h2_style))
story.append(bullets([
    "Resolved an issue where certain pages appeared empty due to a mismatched data source \u2014 content now loads correctly and consistently for all customers.",
]))

# =======================================================================
# ADMIN DASHBOARD
# =======================================================================
story.append(PageBreak())
story.append(Paragraph("Admin Dashboard", h1_style))

story.append(Paragraph("Chat &amp; Messaging", h2_style))
story.append(bullets([
    "Timestamps in chats are now shown in a friendly \u201c2 minutes ago\u201d style, with all \u201cInvalid date\u201d and future-time display bugs resolved.",
    "Toast pop-ups now appear for new incoming messages so nothing gets missed while working in another part of the dashboard.",
]))

story.append(Paragraph("Notifications", h2_style))
story.append(bullets([
    "Notifications now update in real time \u2014 no more refreshing the page to see new alerts.",
    "<b>\u201cMark all as read\u201d</b> button added to the notifications dropdown to clear the list in one click.",
    "Unread notifications are now visually distinct and show the full message (no more cut-off text).",
    "Fixed duplicate notification pop-ups in Chrome and several crash issues with the unread counter.",
]))

story.append(Paragraph("Wallet &amp; Transactions", h2_style))
story.append(bullets([
    "New <b>admin wallet transactions page</b> so you can review wallet activity across all users from one place.",
    "Cleaner transactions table with improved readability and polished styling.",
    "Removed confusing status column and filter from the transactions page to simplify the view.",
]))

story.append(Paragraph("Sellers &amp; Orders", h2_style))
story.append(bullets([
    "Account status column added to the sellers table so you can see which sellers are active/inactive at a glance.",
    "Removed the \u201cfast create order\u201d button from the order details page to prevent accidental duplicate orders.",
    "Decline order button now shows a loading state so it\u2019s clear the action is processing.",
]))

story.append(Paragraph("Dashboard Navigation", h2_style))
story.append(bullets([
    "Shortcut cards added to the home page for faster access to the most-used areas.",
    "Sidebar cleaned up: shorter labels, reordered items, and \u201cPurchase Orders\u201d renamed to \u201cPOs\u201d for quicker scanning.",
]))

story.append(Paragraph("Stability &amp; Reliability", h2_style))
story.append(bullets([
    "Fixed the issue where users were being stuck in a logout loop.",
    "Improved session handling so the dashboard stays in sync with the backend and fails gracefully.",
    "Upgraded underlying messaging infrastructure for better speed and reliability going forward.",
    "Resolved several minor display issues (role dropdowns, pagination, product exports, date warnings).",
]))

# =======================================================================
# BACKEND & PLATFORM
# =======================================================================
story.append(PageBreak())
story.append(Paragraph("Backend &amp; Platform", h1_style))

story.append(Paragraph("Reliability &amp; Order Accuracy", h2_style))
story.append(bullets([
    "<b>Fixed order confirmation &amp; deposit calculations</b> \u2014 buyers are charged the correct deposit and orders reach confirmed status reliably, reducing disputes and manual corrections.",
    "<b>Automatic refunds on canceled orders</b> \u2014 protects customer trust and removes the need for finance-team intervention on cancellations.",
    "<b>Resilient order decline flow</b> \u2014 declined orders complete successfully even when the shipping provider fails, and admins are automatically notified if a shipment cancellation needs manual attention.",
    "<b>Purchase Order (PO) document generation fixed</b> \u2014 sellers receive properly named PO PDFs when orders confirm, eliminating missing documents.",
    "<b>Multiparty deal accuracy</b> \u2014 correct quantity deduction, accurate minimum-submission detection, and cleaner deal closure, preventing inventory mismatches on multi-seller deals.",
]))

story.append(Paragraph("Financial &amp; Wallet Protections", h2_style))
story.append(bullets([
    "<b>Overdraft protection on wallet withdrawals</b> \u2014 prevents negative balances and accidental over-charging of user wallets.",
    "<b>Canceled submissions can rejoin deals</b> \u2014 users who cancel by mistake can re-enter a deal without admin intervention.",
    "<b>Price slab and deal-transition fixes</b> \u2014 pricing is now enforced correctly across tiered quantity deals, preventing revenue leakage.",
]))

story.append(Paragraph("Admin Tools", h2_style))
story.append(bullets([
    "<b>Admin wallet transactions dashboard endpoint</b> \u2014 full visibility into every wallet movement across the platform for auditing and support.",
    "<b>Admin wallet deposit tool</b> \u2014 admins can credit user wallets directly when needed (e.g. promotional balance, manual refunds).",
    "<b>Shared support inbox</b> \u2014 all admins can see and reply to support chats, removing the bottleneck on a single team member.",
]))

story.append(Paragraph("Communication &amp; Notifications", h2_style))
story.append(bullets([
    "<b>Migrated chat and notifications to Firebase</b> \u2014 real-time messaging and push notifications are more reliable, work offline, and deliver to mobile devices even when users aren\u2019t actively in the app.",
    "<b>Push notifications for offline chat users</b> \u2014 customers receive alerts on their phones when they miss a message, improving response times.",
    "<b>Price list notifications now sent at the right moment</b> \u2014 sellers get the buyer price list exactly when a deal enters the waiting stage, not on a delayed daily schedule. Empty deals no longer generate noise.",
]))

story.append(Paragraph("Security &amp; Session Management", h2_style))
story.append(bullets([
    "<b>Standardized error messages across the API</b> \u2014 clearer, more consistent error feedback for users and for the frontend team.",
    "<b>Suspended company handling improved</b> \u2014 suspended accounts receive a proper access-denied response instead of a confusing \u201cgone\u201d message.",
    "<b>Real-time session invalidation</b> \u2014 when an admin suspends a user or changes their role, the change takes effect immediately across all their devices instead of waiting for them to log out.",
    "<b>Lean session snapshot endpoint</b> \u2014 the app can quickly refresh user status without a heavy data reload, improving performance.",
]))

story.append(Paragraph("Performance &amp; Stability", h2_style))
story.append(bullets([
    "<b>API rate limit doubled (60 \u2192 120 requests/minute)</b> \u2014 smoother experience for power users and admin dashboards under heavy load.",
    "Removed a harmful cleanup job that was deleting valid submission data.",
    "<b>Fixed declined-order viewing crashes</b> \u2014 admins can now review declined orders without errors.",
    "<b>Product catalog stability fix</b> \u2014 catalog pages load correctly even when a category has been removed.",
    "<b>Auto-match crash fixed</b> \u2014 automatic deal matching runs reliably without interruption.",
]))

story.append(Paragraph("Quality Assurance", h2_style))
story.append(bullets([
    "<b>Comprehensive end-to-end test suite added</b> \u2014 covers buyer and seller flows plus admin dashboard, catching regressions before they reach production.",
]))

# Build
doc = SimpleDocTemplate(
    OUTPUT, pagesize=A4,
    leftMargin=2*cm, rightMargin=2*cm,
    topMargin=2*cm, bottomMargin=2*cm,
    title="VYA Platform Updates - Past Month",
    author="VYA Team",
)
doc.build(story)
print(f"Wrote {OUTPUT}")
