from __future__ import annotations

from pathlib import Path

from docx import Document
from docx.enum.section import WD_SECTION
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Inches, Pt, RGBColor


ROOT = Path(__file__).resolve().parents[1]
OUT_DIR = ROOT / "docs"
DOCX_PATH = OUT_DIR / "BizNovia_A_to_Z_User_Manual.docx"
MD_PATH = OUT_DIR / "BizNovia_A_to_Z_User_Manual.md"


def set_cell_shading(cell, fill: str) -> None:
    tc_pr = cell._tc.get_or_add_tcPr()
    shd = OxmlElement("w:shd")
    shd.set(qn("w:fill"), fill)
    tc_pr.append(shd)


def set_cell_text(cell, text: str, bold: bool = False) -> None:
    cell.text = ""
    paragraph = cell.paragraphs[0]
    run = paragraph.add_run(text)
    run.bold = bold
    run.font.name = "Nirmala UI"
    run._element.rPr.rFonts.set(qn("w:eastAsia"), "Nirmala UI")
    run.font.size = Pt(9)


def add_table(doc: Document, headers: list[str], rows: list[list[str]]) -> None:
    table = doc.add_table(rows=1, cols=len(headers))
    table.style = "Table Grid"
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    for index, header in enumerate(headers):
        cell = table.rows[0].cells[index]
        set_cell_shading(cell, "E8EEF5")
        set_cell_text(cell, header, bold=True)
        cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

    for row in rows:
        cells = table.add_row().cells
        for index, value in enumerate(row):
            set_cell_text(cells[index], value)
            cells[index].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.TOP

    doc.add_paragraph()


def add_bullets(doc: Document, items: list[str]) -> None:
    for item in items:
        paragraph = doc.add_paragraph(style="List Bullet")
        paragraph.add_run(item)


def add_steps(doc: Document, items: list[str]) -> None:
    for item in items:
        paragraph = doc.add_paragraph(style="List Number")
        paragraph.add_run(item)


def add_heading(doc: Document, text: str, level: int = 1) -> None:
    doc.add_heading(text, level=level)


def add_para(doc: Document, text: str = "") -> None:
    doc.add_paragraph(text)


def setup_styles(doc: Document) -> None:
    section = doc.sections[0]
    section.top_margin = Inches(0.8)
    section.bottom_margin = Inches(0.8)
    section.left_margin = Inches(0.8)
    section.right_margin = Inches(0.8)

    styles = doc.styles
    styles["Normal"].font.name = "Nirmala UI"
    styles["Normal"]._element.rPr.rFonts.set(qn("w:eastAsia"), "Nirmala UI")
    styles["Normal"].font.size = Pt(10)
    styles["Normal"].paragraph_format.space_after = Pt(5)
    styles["Normal"].paragraph_format.line_spacing = 1.12

    for style_name, size, color in [
        ("Heading 1", 16, "1F4D78"),
        ("Heading 2", 13, "2E74B5"),
        ("Heading 3", 11, "1F4D78"),
    ]:
        style = styles[style_name]
        style.font.name = "Nirmala UI"
        style._element.rPr.rFonts.set(qn("w:eastAsia"), "Nirmala UI")
        style.font.size = Pt(size)
        style.font.color.rgb = RGBColor.from_string(color)
        style.font.bold = True
        style.paragraph_format.space_before = Pt(8)
        style.paragraph_format.space_after = Pt(4)

    for style_name in ["List Bullet", "List Number"]:
        style = styles[style_name]
        style.font.name = "Nirmala UI"
        style._element.rPr.rFonts.set(qn("w:eastAsia"), "Nirmala UI")
        style.font.size = Pt(10)
        style.paragraph_format.space_after = Pt(3)


def cover(doc: Document) -> None:
    title = doc.add_paragraph()
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = title.add_run("BizNovia A to Z User Manual")
    run.bold = True
    run.font.name = "Nirmala UI"
    run._element.rPr.rFonts.set(qn("w:eastAsia"), "Nirmala UI")
    run.font.size = Pt(24)
    run.font.color.rgb = RGBColor.from_string("0B2545")

    subtitle = doc.add_paragraph()
    subtitle.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = subtitle.add_run("Business Operating System SaaS - Functional Documentation")
    run.font.name = "Nirmala UI"
    run._element.rPr.rFonts.set(qn("w:eastAsia"), "Nirmala UI")
    run.font.size = Pt(12)

    doc.add_paragraph()
    add_table(
        doc,
        ["Item", "Details"],
        [
            ["Project", "BizNovia modular SaaS"],
            ["Backend", "Laravel API in backend/"],
            ["Frontend", "Vue app in frontend/"],
            ["API", "Versioned /api/v1 JSON API for web and future mobile apps"],
            ["Audience", "Admin, tenant/company users, employees, customers, developers"],
        ],
    )
    doc.add_page_break()


def manual_sections() -> list[dict]:
    return [
        {
            "title": "1. Application Overview",
            "paras": [
                "BizNovia একটি modular Business Operating System SaaS. এর উদ্দেশ্য হলো ছোট ও মাঝারি ব্যবসার invoice, POS, inventory, accounting, CRM, reports, notification এবং customer portal এক জায়গা থেকে চালানো।",
                "Application টি API-first হিসেবে তৈরি, তাই একই backend API দিয়ে web frontend ছাড়াও future mobile app build করা যাবে।",
            ],
            "bullets": [
                "Backend থাকে backend folder-এ এবং Laravel module structure follow করে।",
                "Frontend থাকে frontend folder-এ এবং Vue module structure follow করে।",
                "প্রতিটি tenant/company আলাদা workspace হিসেবে কাজ করে।",
                "Feature এবং permission দুই স্তরে access control করা হয়।",
            ],
        },
        {
            "title": "2. User Types and Login Accounts",
            "table": {
                "headers": ["User Type", "Account আছে?", "Dashboard", "Main Purpose"],
                "rows": [
                    ["Super Admin", "হ্যাঁ", "Super Admin dashboard", "Plans, modules, companies, subscriptions manage করা"],
                    ["Company/Tenant User", "হ্যাঁ", "Workspace dashboard", "নিজ company workspace চালানো"],
                    ["Employee/Admin/Member", "হ্যাঁ", "Permission-based workspace", "Assigned modules ব্যবহার করা"],
                    ["Customer Portal User", "হ্যাঁ, আলাদা portal account", "Customer portal", "নিজ invoice দেখা, profile/password update করা"],
                ],
            },
        },
        {
            "title": "3. Core Navigation",
            "paras": [
                "Login করার পরে user Dashboard-এ যায়। Sidebar-এ শুধু সেই module দেখা যায় যেগুলো current plan-এ enabled এবং user permission-এ allowed।",
            ],
            "table": {
                "headers": ["Menu", "Use"],
                "rows": [
                    ["Dashboard", "Business summary, alerts, sales trend, quick module links"],
                    ["Invoices", "Customer, invoice, payment এবং portal account manage"],
                    ["POS", "Product sale, barcode scan, payment, receipt print/export"],
                    ["Inventory", "Product, category, supplier, purchase, stock adjustment"],
                    ["Finance", "Accounts, ledger, expense, transfer, finance summary"],
                    ["CRM", "Lead, stage, activity, follow-up, customer conversion"],
                    ["Reports", "Overview, sales, inventory, CRM reports"],
                    ["Notifications", "Business alerts and notifications"],
                    ["Companies", "Workspace switch, company create, plan switch"],
                    ["Employees", "Team member add/remove/role update"],
                    ["Settings", "Company profile, defaults, alert rules"],
                ],
            },
        },
        {
            "title": "4. Authentication Functions",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Register", "নতুন tenant user account create করে token দেয়।", "Register page-এ name, email, password, confirm password দিয়ে submit করুন। এরপর onboarding page-এ company create করুন।"],
                    ["Login", "Existing user login করে workspace access দেয়।", "Email/password দিয়ে login করুন। Login redirect query থাকলে safe internal route-এ যায়।"],
                    ["Forgot Password", "Password reset link email করে।", "Forgot password page-এ email দিয়ে Send Reset Link চাপুন।"],
                    ["Reset Password", "Valid reset token দিয়ে new password set করে।", "Email link থেকে open করে new password এবং confirmation দিন।"],
                    ["Email Verification", "Signed verification link দিয়ে email verified করে।", "Email থেকে link open করলে verify endpoint hit হয়। Success হলে dashboard button দেখা যায়।"],
                    ["Logout", "Current Sanctum token revoke করে।", "Topbar Logout button চাপুন।"],
                ],
            },
        },
        {
            "title": "5. Company, Tenant, and Subscription",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Company Create", "নতুন business workspace তৈরি করে starter subscription attach করে।", "Companies বা onboarding page থেকে company name, email, phone, currency, timezone দিন।"],
                    ["Company Switch", "User-এর একাধিক workspace থাকলে active company switch করে।", "Companies page-এ target company row থেকে Use চাপুন।"],
                    ["Tenant Current", "Current company, plan, feature, permission load করে।", "Login/company switch-এর পরে frontend automatically call করে। Mobile app-ও এটা ব্যবহার করবে।"],
                    ["Plan Switch", "Current company subscription অন্য plan-এ switch করে।", "Companies বা Locked Module page থেকে plan select করে Use Plan/Upgrade চাপুন।"],
                    ["Locked Module", "Plan-এ module না থাকলে upgrade page দেখায়।", "Locked page eligible plans দেখায়; owner/admin plan switch করতে পারে।"],
                ],
            },
        },
        {
            "title": "6. Dashboard",
            "paras": [
                "Dashboard হলো current workspace-এর command center. এটি enabled features অনুযায়ী data দেখায়। Locked modules direct open না করে locked state দেখায়।",
            ],
            "table": {
                "headers": ["Widget/Function", "Meaning", "How to Use"],
                "rows": [
                    ["POS Sales", "Selected period POS sales total", "Reports feature enabled থাকলে auto show হয়।"],
                    ["Invoice Due", "Unpaid invoice amount", "Invoice collection follow-up করতে ব্যবহার করুন।"],
                    ["Open Leads", "CRM open leads count", "CRM review করার signal।"],
                    ["Unread Notifications", "Unread notifications count", "Notifications page open করে read/manage করুন।"],
                    ["Account Balance", "Accounting accounts balance", "Finance page থেকে details দেখুন।"],
                    ["Operations Links", "Feature-aware quick links", "Enabled module-এ click করলে module open হয়, disabled হলে locked indication থাকে।"],
                ],
            },
        },
        {
            "title": "7. Invoice Module",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Customer List", "Company customers list/filter করে।", "Invoices page-এর Customers section থেকে search/filter করুন।"],
                    ["Create Customer", "Customer record create করে।", "Name, email, phone, address দিয়ে Add Customer চাপুন।"],
                    ["Update/Deactivate Customer", "Customer details বা status update করে।", "Customer row থেকে Edit করে save/deactivate করুন।"],
                    ["Create Invoice", "Item quantity, price, tax, discount থেকে invoice totals calculate করে।", "Customer optional, issue/due date, items add করে Create Invoice চাপুন।"],
                    ["Record Payment", "Invoice paid_total/due_total/status update করে। Accounting account দিলে ledger inflow হয়।", "Invoice row থেকে payment amount/method/account দিয়ে Mark Paid/Record Payment।"],
                    ["Cancel Invoice", "Unpaid invoice cancel করে। Paid invoice cancel করা যায় না।", "Invoice status eligible হলে Cancel চাপুন।"],
                    ["Export HTML", "Printable invoice HTML open করে।", "Export/Print action ব্যবহার করুন।"],
                    ["Customer Portal Account", "Customer login credential create/update/revoke করে।", "Customer row থেকে portal account section ব্যবহার করুন।"],
                ],
            },
        },
        {
            "title": "8. POS Module and Barcode Scanner",
            "paras": [
                "POS module product sale complete করে stock কমায়। Barcode scanner USB/Bluetooth keyboard input হিসেবে কাজ করে। Scanner field focus থাকলে scan শেষে Enter দিলে product auto cart-এ যোগ হয়।",
            ],
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Product Search", "Name, SKU, barcode দিয়ে product filter করে।", "Product Search field-এ টাইপ করুন।"],
                    ["Barcode Scan", "Exact active product lookup by barcode/SKU করে cart-এ add করে।", "Barcode Scanner field focus করুন, scan করুন, scanner Enter পাঠালে item add হবে।"],
                    ["Add to Cart", "Selected product cart line item হিসেবে add করে।", "Product list থেকে Add চাপুন। Stock না থাকলে error দেখাবে।"],
                    ["Cart Edit", "Qty, price, discount, tax edit করে line total update করে।", "Cart row-এর inputs update করুন।"],
                    ["Complete Sale", "Sale create, stock decrease, optional account inflow করে।", "Payment method, paid amount, account select করে Complete Sale চাপুন।"],
                    ["Void Sale", "Sale void করে stock এবং ledger reverse করে।", "Recent Sales থেকে eligible sale-এ Void চাপুন।"],
                    ["Print/Export Receipt", "Receipt preview/HTML export/print করে।", "Recent Sales row থেকে Preview, Export, Print ব্যবহার করুন।"],
                ],
            },
        },
        {
            "title": "9. Inventory Module",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Categories", "Product grouping manage করে।", "Category name add করুন; edit/deactivate করা যায়।"],
                    ["Products", "SKU, barcode, price, stock threshold সহ product manage করে।", "Create Product form থেকে product create করুন; barcode field scanner/POS lookup-এ কাজে লাগে।"],
                    ["Product Lookup", "Barcode/SKU দিয়ে exact active product find করে।", "POS barcode scan internally `/inventory/products/lookup?code=` ব্যবহার করে।"],
                    ["Stock Adjustment", "Manual stock plus/minus করে stock movement রাখে।", "Products list থেকে +1/-1 বা adjust action ব্যবহার করুন।"],
                    ["Suppliers", "Supplier info manage করে।", "Create Supplier form থেকে add; list থেকে edit করুন।"],
                    ["Receive Purchase", "Purchase items receive করে stock বাড়ায়। Account দিলে expense/outflow ledger হয়।", "Supplier/account/date/items দিয়ে Receive চাপুন।"],
                    ["Cancel Purchase", "Purchase reverse করে stock এবং ledger undo করে।", "Purchase row থেকে Cancel চাপুন; stock enough না থাকলে cancel হবে না।"],
                    ["CSV Export", "Products/purchases export করে।", "Filters apply করে Export CSV চাপুন।"],
                    ["Low Stock", "Threshold equal/below products দেখায়।", "Low Stock panel বা low stock filter ব্যবহার করুন।"],
                ],
            },
        },
        {
            "title": "10. Accounting Module",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Summary", "Income, expense, net profit দেখায়।", "Date filter apply করলে selected period summary দেখায়।"],
                    ["Financial Accounts", "Cash/bank/mobile wallet/card accounts manage করে।", "Account name/type/opening balance দিয়ে Add Account।"],
                    ["Manual Ledger Entry", "Manual income/expense/adjustment/transfer entry করে।", "Account, date, amount, type, direction, description দিয়ে Save Entry।"],
                    ["Account Transfer", "এক account থেকে অন্য account-এ transfer করে two ledger rows তৈরি করে।", "From, To, amount, date দিয়ে Transfer চাপুন।"],
                    ["Expense Categories", "Expense classification manage করে।", "Category add/edit/deactivate করুন।"],
                    ["Record Expense", "Expense entry করে; account দিলে ledger outflow sync করে।", "Category/account/date/amount/payment/vendor দিয়ে Save Expense।"],
                    ["Void Expense", "Expense void করে related ledger reverse/remove করে।", "Expense list থেকে Void চাপুন।"],
                    ["CSV Export", "Ledger/expenses export করে।", "Filters apply করে Export CSV চাপুন।"],
                ],
            },
        },
        {
            "title": "11. CRM Module",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Create Lead", "Prospect/customer opportunity create করে।", "Name, company, email, phone, source, value, follow-up date দিন।"],
                    ["Lead Board", "New, Contacted, Qualified, Proposal, Won, Lost stage অনুযায়ী leads group করে।", "Stage card থেকে lead Open করুন।"],
                    ["Stage Update", "Lead progress update করে; Won/Lost হলে status closed হয়।", "Lead Details select dropdown থেকে stage change করুন।"],
                    ["Activity Add", "Call/email/meeting/task/note activity add করে।", "Subject, type, description, next follow-up date দিয়ে Add Activity।"],
                    ["Follow-up Tracking", "Due follow-up indicators দেখায়।", "Follow-ups Due metric দেখে CRM review করুন।"],
                    ["Convert to Customer", "Won lead থেকে invoice customer create করে।", "Lead Details থেকে Convert Customer চাপুন।"],
                ],
            },
        },
        {
            "title": "12. Reports Module",
            "table": {
                "headers": ["Report", "Description", "How to Use"],
                "rows": [
                    ["Overview", "Sales, invoice due, payments, purchases, stock, CRM totals।", "Date range/preset select করে Apply করুন।"],
                    ["Sales", "Daily sales and payment method breakdown।", "Sales section থেকে trend দেখুন।"],
                    ["Inventory", "Products, stock value, low stock, purchases।", "Inventory report section review করুন।"],
                    ["CRM", "Lead counts, pipeline, upcoming follow-ups।", "CRM report section review করুন।"],
                    ["Print", "Report print view।", "Print button ব্যবহার করুন।"],
                ],
            },
        },
        {
            "title": "13. Notifications Module",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Notification List", "Manual notifications and system alerts দেখায়।", "Notifications page open করুন।"],
                    ["Live Business Alerts", "Low stock, invoice due, CRM follow-up alert generate করে।", "Company Settings alert toggles দিয়ে control করুন।"],
                    ["Read/Unread", "Notifications read state manage করে।", "Mark read বা Mark all read ব্যবহার করুন।"],
                    ["Create Notification", "Manual notification create করে।", "Type, title, message, action URL দিয়ে create করুন।"],
                    ["Auto Refresh", "Page periodic refresh করে latest alerts আনে।", "Manual Refresh button-ও আছে।"],
                ],
            },
        },
        {
            "title": "14. Settings, Employees, and Workspace Admin",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Company Settings", "Profile, currency, timezone, prefixes, tax, payment terms, alert rules update করে।", "Settings page থেকে edit করে Save Settings।"],
                    ["Business Prefixes", "Invoice/POS/Purchase/Expense number prefix control করে।", "Settings > Business Defaults।"],
                    ["Alert Rules", "Low stock, invoice due, CRM follow-up alerts on/off করে।", "Settings > Alert Rules checkboxes।"],
                    ["Employees", "Owner/admin/member team manage করে।", "Employees page থেকে add, role update, remove। Owner remove করা যায় না।"],
                    ["Companies", "Workspace list, select, create, plan switch।", "Companies page ব্যবহার করুন।"],
                    ["Onboarding", "First company setup flow।", "Registration-এর পর company and plan choose করুন।"],
                ],
            },
        },
        {
            "title": "15. Customer Portal",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Portal Login", "Customer own portal account দিয়ে login করে।", "Customer portal login page-এ email/password দিন।"],
                    ["Portal Dashboard", "Total/unpaid/overdue/due invoice summary দেখায়।", "Login করার পর dashboard দেখুন।"],
                    ["Invoice List", "Customer only own invoices দেখতে পারে।", "Status/search/pagination দিয়ে invoice খুঁজুন।"],
                    ["Invoice Detail", "Invoice items/payment history দেখায়।", "Invoice row থেকে View/Open করুন।"],
                    ["Profile Update", "Customer name/email/phone update করে।", "Profile section edit করুন।"],
                    ["Password Change", "Current password verify করে new password set করে।", "Password form submit করুন।"],
                ],
            },
        },
        {
            "title": "16. Super Admin",
            "table": {
                "headers": ["Function", "Description", "How to Use"],
                "rows": [
                    ["Summary", "Platform companies, subscriptions, plans, MRR।", "Super Admin page top metrics।"],
                    ["Plan Management", "SaaS plans create/update/activate/deactivate।", "Plan form and plan list actions ব্যবহার করুন।"],
                    ["Feature Management", "Modules/features enable/disable করে।", "Features section toggle/update।"],
                    ["Company Status", "Tenant active/inactive status control।", "Companies section status update।"],
                    ["Subscription Management", "Tenant plan, billing cycle, status update।", "Subscriptions section controls।"],
                ],
            },
        },
        {
            "title": "17. Roles, Features, and Permissions",
            "paras": [
                "Access control দুই স্তরে কাজ করে: subscription plan feature enabled কিনা, এবং user permission আছে কিনা। Sidebar, route guard এবং backend middleware একই rule enforce করে।",
            ],
            "table": {
                "headers": ["Permission", "Allows"],
                "rows": [
                    ["*.view", "Module data দেখা/list/detail/export করা"],
                    ["*.manage", "Create/update/delete/cancel/void/receive/payment actions করা"],
                    ["settings.manage", "Company settings update করা"],
                    ["users.manage", "Employees add/remove/role update করা"],
                    ["subscriptions.manage", "Company plan switch করা"],
                    ["super-admin", "Platform-level admin endpoints and UI access"],
                ],
            },
        },
        {
            "title": "18. Common Workflows",
            "steps": [
                "New user: Register -> verify email -> create company in onboarding -> dashboard open.",
                "New product sale: Inventory product create with barcode -> POS barcode scan -> Complete Sale -> stock decreases.",
                "Purchase stock: Inventory Receive Purchase -> stock increases -> optional accounting outflow created.",
                "Invoice collection: Create customer -> create invoice -> record payment -> invoice due total updates.",
                "Customer portal: Create portal account -> give login to customer -> customer views own invoices.",
                "Team setup: Owner opens Employees -> adds member/admin -> permissions apply automatically.",
                "Upgrade module: Locked page opens -> owner/admin chooses plan -> route unlocks after plan switch.",
            ],
        },
        {
            "title": "19. API and Mobile App Usage",
            "paras": [
                "Mobile app একই `/api/v1` backend ব্যবহার করবে। Tenant user token এবং customer portal token আলাদা রাখতে হবে।",
            ],
            "steps": [
                "Tenant app login: POST /auth/login.",
                "Token store করুন and Authorization Bearer header পাঠান।",
                "GET /companies দিয়ে company list নিন।",
                "Selected company id `X-Company-ID` header হিসেবে পাঠান।",
                "GET /tenant/current দিয়ে features/permissions hydrate করুন।",
                "403 feature response পেলে locked/upgrade screen দেখান।",
            ],
        },
        {
            "title": "20. Frontend and API Routes",
            "paras": [
                "এই section-এ web app page routes এবং backend API route groups দেওয়া হলো। Frontend routes browser URL হিসেবে ব্যবহার হয়; API routes mobile app, web frontend, and integrations থেকে call করা যাবে।",
            ],
            "table": {
                "headers": ["Route Type", "Route", "Purpose"],
                "rows": [
                    ["Frontend", "/", "Authenticated workspace dashboard"],
                    ["Frontend", "/login", "Tenant user login"],
                    ["Frontend", "/register", "Tenant user registration"],
                    ["Frontend", "/forgot-password", "Password reset request"],
                    ["Frontend", "/reset-password", "Set new password from reset token"],
                    ["Frontend", "/verify-email", "Email verification result page"],
                    ["Frontend", "/onboarding", "First company/workspace setup"],
                    ["Frontend", "/invoices", "Invoice and customer management"],
                    ["Frontend", "/pos", "POS sale and barcode scanner"],
                    ["Frontend", "/inventory", "Inventory, stock, suppliers, purchases"],
                    ["Frontend", "/finance", "Accounting, ledger, expense, transfer"],
                    ["Frontend", "/crm", "CRM leads and activities"],
                    ["Frontend", "/reports", "Business reports"],
                    ["Frontend", "/notifications", "Notifications and live alerts"],
                    ["Frontend", "/locked", "Locked module upgrade page"],
                    ["Frontend", "/settings", "Company settings"],
                    ["Frontend", "/settings/companies", "Company/workspace switch and plans"],
                    ["Frontend", "/settings/members", "Employees/team management"],
                    ["Frontend", "/super-admin", "Platform super admin panel"],
                    ["Frontend", "/customer-portal/login", "Customer portal login"],
                    ["Frontend", "/customer-portal", "Customer portal dashboard"],
                    ["Frontend", "/customer-portal/invoices/:id", "Customer invoice detail"],
                    ["API", "GET /api/v1/health", "Backend health check"],
                    ["API Auth", "POST /api/v1/auth/register", "Register tenant user"],
                    ["API Auth", "POST /api/v1/auth/login", "Login tenant user"],
                    ["API Auth", "POST /api/v1/auth/forgot-password", "Request reset link"],
                    ["API Auth", "POST /api/v1/auth/reset-password", "Reset password"],
                    ["API Auth", "GET /api/v1/auth/me", "Current user profile"],
                    ["API Tenant", "GET /api/v1/plans", "Public active plans"],
                    ["API Tenant", "GET/POST /api/v1/companies", "List/create workspaces"],
                    ["API Tenant", "GET /api/v1/tenant/current", "Current tenant context"],
                    ["API Tenant", "PATCH /api/v1/tenant/settings", "Update company settings"],
                    ["API Tenant", "POST /api/v1/tenant/subscription/switch-plan", "Switch company plan"],
                    ["API Tenant", "GET/POST/PATCH/DELETE /api/v1/tenant/members", "Team member management"],
                    ["API Invoice", "/api/v1/customers, /api/v1/invoices", "Customers, invoices, payments, export"],
                    ["API Customer Portal", "/api/v1/customer-portal/*", "Customer login, dashboard, invoices, profile"],
                    ["API POS", "/api/v1/pos/sales", "Sales, void, receipt export"],
                    ["API Inventory", "/api/v1/inventory/*", "Categories, products, barcode lookup, stock, purchases"],
                    ["API Accounting", "/api/v1/accounting/*", "Accounts, ledger, transfers, expenses, summary"],
                    ["API CRM", "/api/v1/crm/*", "Lead summary, leads, activities, conversion"],
                    ["API Reports", "/api/v1/reports/*", "Overview, sales, inventory, CRM reports"],
                    ["API Notifications", "/api/v1/notifications/*", "Notifications, alerts, read state"],
                    ["API Super Admin", "/api/v1/super-admin/*", "Platform plans, features, companies, subscriptions"],
                ],
            },
        },
        {
            "title": "21. Troubleshooting",
            "table": {
                "headers": ["Problem", "Likely Cause", "Fix"],
                "rows": [
                    ["Registration/Login failed", "Validation, duplicate email, backend down", "Backend health check করুন, exact API error পড়ুন।"],
                    ["Module locked", "Current plan feature missing", "Companies/Locked page থেকে plan upgrade করুন।"],
                    ["Menu missing", "User permission নেই বা feature disabled", "Employee role/plan check করুন।"],
                    ["Barcode scan not working", "Input focus নেই বা product barcode save নেই", "POS Barcode Scanner field focus করুন; Inventory product barcode verify করুন।"],
                    ["Stock negative error", "Sale/adjust/cancel quantity stock থেকে বেশি", "Inventory stock review করে quantity ঠিক করুন।"],
                    ["Customer cannot login", "Portal account inactive/password wrong", "Customer portal account update/revoke/reset করুন।"],
                    ["Email not received", "MAIL_MAILER log/local config", "Production mail provider configure করুন।"],
                ],
            },
        },
        {
            "title": "22. Developer and Deployment Notes",
            "bullets": [
                "Local frontend: http://127.0.0.1:5174.",
                "Local backend: http://127.0.0.1:8000.",
                "Run backend tests with `php artisan test`.",
                "Run frontend build with `npm run build`.",
                "Production deployment needs APP_ENV=production, APP_DEBUG=false, real mail config, queue worker, scheduler, SSL/domain, and frontend origin in CORS_ALLOWED_ORIGINS.",
                "Full endpoint reference is available in docs/API_REFERENCE.md.",
            ],
        },
    ]


def build_docx() -> None:
    doc = Document()
    setup_styles(doc)
    cover(doc)

    add_heading(doc, "Table of Contents", 1)
    for item in manual_sections():
        add_para(doc, item["title"])
    doc.add_page_break()

    for section in manual_sections():
        add_heading(doc, section["title"], 1)
        for paragraph in section.get("paras", []):
            add_para(doc, paragraph)
        if "bullets" in section:
            add_bullets(doc, section["bullets"])
        if "steps" in section:
            add_steps(doc, section["steps"])
        if "table" in section:
            add_table(doc, section["table"]["headers"], section["table"]["rows"])

    doc.add_section(WD_SECTION.CONTINUOUS)
    footer = doc.sections[-1].footer.paragraphs[0]
    footer.alignment = WD_ALIGN_PARAGRAPH.CENTER
    footer.add_run("BizNovia A to Z User Manual")
    doc.save(DOCX_PATH)


def build_markdown() -> None:
    lines: list[str] = [
        "# BizNovia A to Z User Manual",
        "",
        "Business Operating System SaaS - Functional Documentation",
        "",
    ]
    for section in manual_sections():
        lines.extend([f"## {section['title']}", ""])
        for paragraph in section.get("paras", []):
            lines.extend([paragraph, ""])
        for bullet in section.get("bullets", []):
            lines.append(f"- {bullet}")
        if section.get("bullets"):
            lines.append("")
        for index, step in enumerate(section.get("steps", []), start=1):
            lines.append(f"{index}. {step}")
        if section.get("steps"):
            lines.append("")
        if "table" in section:
            headers = section["table"]["headers"]
            lines.append("| " + " | ".join(headers) + " |")
            lines.append("| " + " | ".join(["---"] * len(headers)) + " |")
            for row in section["table"]["rows"]:
                lines.append("| " + " | ".join(value.replace("|", "/") for value in row) + " |")
            lines.append("")
    MD_PATH.write_text("\n".join(lines), encoding="utf-8")


if __name__ == "__main__":
    OUT_DIR.mkdir(exist_ok=True)
    build_docx()
    build_markdown()
    print(DOCX_PATH)
    print(MD_PATH)
