"""One-off seed: registers translation_keys (namespace="help", English
source_text only) for the Phase 2 PageInfoButton rollout — ~145 pages across
every feature module, on top of the 5 pilot pages seeded by
seed_translations_help.py. No translation_values are inserted here (English
never needs one — the frontend's t(key, fallbackText) always falls back to
the English prop). Run seed_translations_help.py first if a fresh tenant
hasn't seeded the pilot pages yet; this script is independent and idempotent
either way.

Usage: docker compose exec api python seed_translations_help_phase2.py
"""
import asyncio
import uuid
from datetime import datetime, timezone

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from ams.core.config import settings

NAMESPACE = "help"

PAGES = {
    # finance
    "capitalization-queue": ("Asset Capitalization Queue", [
        "Assets pending commissioning, ready to be capitalized into active depreciation ledgers.",
    ]),
    "capitalization-review": ("Capitalization Review", [
        "Detailed review of assets pending commissioning, with full lifecycle history.",
    ]),
    "depreciation-exceptions": ("Depreciation Reconciliation", [
        "Compare net book value across the three depreciation books for a period and surface exceptions.",
    ]),
    "depreciation-master": ("Depreciation Master", [
        "Government-mandated depreciation rates per asset class, book, and fiscal year.",
    ]),
    "depreciation-run-wizard": ("Depreciation Run", [
        "Run three-book depreciation for a monthly period.",
        "Idempotent — re-running the same period recalculates and overwrites entries.",
    ]),
    "finance-dashboard": ("Finance", [
        "Depreciation, journals, budgets, and investment planning.",
        "Per-asset financial actions live on each asset's Financials tab.",
    ]),
    "financial-reconciliation": ("Depreciation Book Reconciliation", [
        "Compare closing net book value and depreciation across Companies Act, Income Tax, and Ind AS books.",
    ]),
    "journal-export": ("Journal Export", [
        "Export depreciation and financial journal entries for a period and book.",
    ]),
    "nbv-dashboard": ("Net Book Value — PPE Movement", [
        "Opening net book value, additions, disposals, depreciation, and closing value per asset class for a fiscal year.",
    ]),

    # dashboard — ExecutiveDashboardView's 4 tabs
    "executive-dashboard": ("Executive Management Dashboard", [
        "KPI overview combining accumulated depreciation, budget utilisation, ISO 55001 readiness, and expired warranty count, pulled live from the CFO and auditor dashboard APIs.",
        "Use Export Dashboard to download the CFO dashboard for the current period.",
    ]),
    "asset-value-analysis": ("Asset Valuation & Depreciation Suite", [
        "Net book value broken down by asset class, alongside total accumulated depreciation (Companies Act) and assets still pending commissioning.",
        "Use \"Manage Depreciation Master\" to open the dedicated depreciation module for revaluations or schedule changes.",
    ]),
    "budget-utilization": ("Budget Utilization Dashboard", [
        "Compares approved budget against actual spend and shows the resulting utilisation percentage across the organization.",
        "Use \"Manage Department-Level Budget Allocations\" to drill into per-department budget lines.",
    ]),
    "compliance-status": ("Compliance Status Dashboard", [
        "ISO 55001 readiness score, count of uncustodied assets, and documents expiring within 30 days, plus a table of upcoming compliance deadlines in the next 30 days.",
        "Use \"Open Compliance Center\" to manage individual compliance events and evidence.",
    ]),

    # custody
    "custody-acknowledgements": ("Pending Acknowledgements", [
        "Assets not yet re-acknowledged by their custodian this fiscal year.",
    ]),
    "asset-transfer": ("Custody Transfer Workflow", [
        "Dual sign-off transfer: initiate, then the outgoing custodian releases and the incoming custodian accepts.",
    ]),
    "custody-assigned-assets": ("Assigned Assets", [
        "Every asset ever assigned to a custodian, with its current status.",
    ]),
    "custody-bulk-reassign": ("Bulk Reassign Custody", [
        "Move multiple assets from one custodian to another in one action.",
    ]),
    "custody-history": ("Custody History", [
        "Full chain-of-custody for a selected asset.",
    ]),
    "custody-investigations": ("Audit Investigations", [
        "Custody disputes, mismatches, and other flagged asset events.",
    ]),
    "custody-liability-report": ("Assets in a Person's Care", [
        "Everything this person is currently holding, and what each item is worth.",
    ]),
    "custody-temp-assignments": ("Temporary Custody Assignments", [
        "Assign short-term custody with an automatic expiry date.",
    ]),

    # dashboard remainder
    "asset-portfolio": ("Asset Portfolio", [
        "Live ledger view of enterprise physical assets with valuation and risk profiles.",
    ]),
    "auditor-dashboard": ("Auditor Dashboard", [
        "Compliance, audit log, and ISO 55001 readiness — read-only.",
    ]),
    "ca-dashboard": ("CA Financial Dashboard", [
        "Asset-wise valuation, depreciation across all 3 statutory books, and compliance readiness — read-only.",
    ]),
    "custodian-dashboard": ("Custodian Dashboard", [
        "Your assigned assets, pending transfers, and outstanding acknowledgements.",
        "Click any card to see its records below.",
    ]),
    "planning-dashboard": ("Planning Dashboard", [
        "Strategic asset portfolio planning, lifecycle scenario building, and financial forecasting.",
    ]),
    "scenario-comparison": ("Capex Scenario Comparison", [
        "Select up to 3 logged capex scenarios to compare side by side.",
    ]),

    # audit-compliance
    "ai-intelligence": ("AAMS AI Intelligence", [
        "Predictive maintenance, anomaly detection, and asset lifecycle intelligence.",
    ]),
    "verification-plans": ("Physical Verification Plans", [
        "Create verification plans to physically check assets against records, and verify the audit log's integrity has not been tampered with.",
    ]),
    "asset-audit-findings": ("Audit Findings", [
        "Log and track audit findings — observations, severity, and corrective actions — until they're resolved.",
    ]),
    "audit-history-registry": ("Audit History Registry", [
        "A searchable record of every audit log event, with tools to export a sanitized copy.",
    ]),
    "audit-timeline": ("Audit Timeline", [
        "A chronological timeline of audit events, filterable by resource type.",
    ]),
    "compliance-center": ("Compliance Center", [
        "Document expiry monitoring, statutory calendar, and ISO 55001 organisational readiness.",
    ]),
    "iso-55001-readiness": ("ISO 55001 Readiness Checklist", [
        "Track progress against the ISO 55001 asset management standard with a scored compliance checklist.",
    ]),
    "risk-assets": ("Risk Assets", [
        "High-criticality assets (criticality score 3 or higher) requiring attention.",
    ]),
    "security-vapt": ("Security & VAPT Governance", [
        "Vulnerability findings, scans, framework assessments, security controls, and login/session events.",
    ]),

    # master-data remainder
    "dashboard-config": ("Dashboard Configuration", [
        "Personalize your executive dashboard layout.",
        "Saved to this browser.",
    ]),
    "department-masters": ("Departments", [
        "A department is an organisation unit of type \"department\".",
    ]),
    "generic-masters": ("Generic Masters", [
        "Browse and maintain any of the generic master tables — pick one from the selector on this page.",
    ]),
    "master-dashboard": ("Master Data Dashboard", [
        "Live record counts across master data categories.",
        "Select a category to browse its records.",
    ]),

    # investment-planning + budget
    "capital-plan": ("Capital Plan Registry", [
        "Long-term (10/20/30-year) CapEx forecast scenarios.",
    ]),
    "create-scenario": ("Create Investment Scenario", [
        "Run repair-vs-replace NPV/TCO analysis for a set of assets over a chosen horizon.",
    ]),
    "npv-analysis": ("Renewal Recommendations", [
        "High-criticality assets in poor or critical condition — candidates for a repair-vs-replace NPV analysis.",
    ]),
    "scenario-review": ("Investment Scenario Review", [
        "Repair-vs-replace results per asset, plus an ISO 55001-aligned SAMP capital plan export.",
    ]),
    "tco-analysis": ("Total Cost of Ownership", [
        "TCO comparison across repair/replace options for a scenario's assets.",
    ]),
    "budget-allocation": ("Budget Allocation", [
        "Create budget lines and approve them.",
        "Maker-checker — the approver must differ from the creator.",
    ]),
    "budget-impact": ("Budget Impact", [
        "Year-end forecast (year-to-date actuals plus commitments plus burn rate) and budget-vs-actual variance.",
    ]),
    "virement-approvals": ("Budget Virement", [
        "Request a transfer of approved budget between heads — a different user must approve.",
        "Also includes PFMS sync and zero-based budgeting tools.",
    ]),

    # vendor-contracts
    "create-grn": ("Goods Receipt Note", [
        "Record what actually arrived against an open purchase order.",
    ]),
    "invoice-verification": ("Invoice Verification", [
        "3-way match: invoice vs purchase order vs goods receipt note.",
    ]),
    "po-approvals": ("PO Approval Queue", [
        "Purchase orders awaiting approval decision.",
    ]),
    "pr-approvals": ("PR Approval Queue", [
        "Purchase requisitions awaiting approval decision.",
    ]),
    "procurement-history": ("Procurement History", [
        "Combined transaction log of requisitions and purchase orders.",
    ]),
    "procurement": ("Procurement Dashboard", [
        "Requisition and purchase order activity across the organization.",
    ]),
    "purchase-orders": ("Purchase Orders", [
        "Register of every purchase order issued to vendors, from draft through closure.",
    ]),
    "purchase-requisitions": ("Purchase Requisitions", [
        "Register of internal purchase requests before they become purchase orders.",
    ]),
    "quotation-comparison": ("Quotation Comparison", [
        "Compare vendor quotations side-by-side and award the RFQ.",
    ]),
    "rfq-management": ("RFQ Management", [
        "Solicit vendor quotations for approved purchase requisitions.",
    ]),
    "purchase-order-detail": ("Purchase Order Details", [
        "Full detail view for a single purchase order — line items, approval status, linked goods receipts, and invoices.",
    ]),
    "purchase-requisition-detail": ("Purchase Requisition Details", [
        "Full detail view for a single purchase requisition — requested items, approval status, and linked purchase order.",
    ]),
    "rfq-detail": ("RFQ Details", [
        "Full detail view for a single RFQ — invited vendors, submitted quotations, and comparison.",
    ]),

    # inventory
    "goods-receipt-register": ("Goods Receipt Register", [
        "Record and review incoming stock receipts.",
    ]),
    "inventory-allocations": ("Inventory Allocations", [
        "Track inventory items allocated to a user, capped at each item's available stock.",
    ]),
    "inventory-dashboard": ("Inventory Dashboard", [
        "Live overview of stock items, low-stock alerts, valuation, and recent movements.",
    ]),
    "inventory-history": ("Inventory Transaction History", [
        "Full audit trail of stock movements — receipts, issues, transfers, adjustments, returns.",
    ]),
    "inventory-register": ("Inventory Item Register", [
        "Master list of inventory items with reorder rules and stock actions.",
    ]),
    "inventory-reports": ("Inventory Reports", [
        "Low-stock alerts and inventory valuation, computed live from current stock levels.",
    ]),
    "inventory-requests": ("Inventory Requests", [
        "Requisition, approve, and issue inventory items to requesters.",
    ]),
    "physical-verification": ("Physical Verification", [
        "Scheduled and completed inventory audits, with variance reconciliation.",
    ]),
    "warehouse-management": ("Stock by Location", [
        "Real stock levels per item, grouped by location.",
        "There is no separate warehouse/bin model in this system — location is a direct reference to the Locations master.",
    ]),

    # reports
    "advanced-reports": ("Advanced Standard Reports", [
        "Custodian exceptions, warranty exposure, transfer history, and OData feeds.",
    ]),
    "cag-report-pack": ("CAG Report Pack", [
        "Consolidated asset register, depreciation schedule, and custodian register for a given fiscal period.",
        "Generated on demand and delivered as XLSX/PDF.",
    ]),
    "document-reports": ("Document Expiry Report", [
        "Asset documents expiring or overdue within the selected window.",
    ]),
    "drill-down-reports": ("Drill Down Reports", [
        "Real-time drill-down queries against the underlying asset ledger.",
    ]),
    "planning-reports": ("Planning Reports & History", [
        "CapEx forecast scenarios and asset renewal recommendations.",
    ]),
    "report-builder": ("Report Builder", [
        "Pick a data source, choose columns and filters, preview, then export.",
    ]),
    "reports-analytics": ("AAMS Reports & Analytics", [
        "Standard reports, KPI analytics, custom reports, and scheduled exports.",
    ]),
    "reports": ("AAMS General Reports & Analytics", [
        "Live asset ledger analytics from the CFO dashboard and asset register.",
    ]),
    "scheduled-reports": ("Scheduled Reports", [
        "Manage automated recurring report distribution.",
    ]),

    # master-data — MasterListViews.tsx (11 pages)
    "location-masters": ("Location Master Registers", [
        "Configure and manage facility domains, floor boundaries, and office workspaces.",
    ]),
    "document-masters": ("Document Masters", [
        "Configure legal compliance documents, guarantees, insurance, and retention covenants.",
    ]),
    "approval-queue": ("Master Approvals Queue", [
        "Maker-checker queue across every governed master table — the approver can never be the same user who created the record (GFR Rule 21).",
        "There is no \"reject\" action; declining a change means leaving it unapproved.",
    ]),
    "master-records": ("Master Data Records", [
        "Consolidated repository of core classification categories used across operational ledger sheets.",
    ]),
    "asset-classes": ("Asset Classes", [
        "Configure asset groupings, depreciation parameters, and standardized operational lives.",
    ]),
    "asset-categories": ("Asset Categories", [
        "Sub-groups of an Asset Class — governed via maker-checker approval.",
    ]),
    "asset-subcategories": ("Asset Sub-Categories", [
        "Finer-grained groupings within an Asset Category.",
    ]),
    "vendor-masters": ("Vendor Masters Registry", [
        "Registry of authorized enterprise suppliers, maintenance vendors, and spare-parts deliverers.",
    ]),
    "tax-masters": ("Tax Masters", [
        "GST rate slabs and HSN/SAC code lookups.",
        "Read-only — maintained via GSTN sync (Financial Masters page), not edited here.",
    ]),
    "validation-errors": ("Check a Bulk Upload", [
        "Uploaded a spreadsheet of assets? Paste its reference number below to see which rows went in and which had a problem, so you can fix and re-upload those rows.",
    ]),
    "financial-masters": ("Financial Masters", [
        "Chart of accounts, cost centres, and fiscal period calendar.",
        "Accounts and fiscal periods are read-only lookups maintained via GSTN/finance system sync; cost centres can be created here.",
    ]),

    # administration
    "executive-history": ("Executive History", [
        "Real system audit trail — every mutating API call, hash-chained and tamper-evident.",
    ]),
    "permission-catalog": ("Permission Catalog", [
        "The full list of permissions across every module — the same catalog Role Create/Edit pull from.",
    ]),
    "roles": ("Role Management", [
        "The register of security roles across the system and the permissions each one grants.",
    ]),
    "users": ("User Management", [
        "Manage enterprise users, their roles, status, and access.",
    ]),
    "settings": ("Settings", [
        "Application branding, map provider, and security policy configuration.",
    ]),
    "roles-create": ("Create Role", [
        "Define a new security role and the permissions it grants.",
    ]),
    "roles-edit": ("Edit Security Role", [
        "Change a role's name, description, or permissions.",
    ]),
    "role-detail": ("Inspect Security Profile", [
        "Read-only view of a role's permissions and the users currently assigned to it.",
    ]),
    "role-permissions-edit": ("Edit Permissions", [
        "Assign or remove individual permissions for this role.",
    ]),
    "users-create": ("Create User", [
        "Register a new enterprise user account with specific role-based permissions and credentials.",
    ]),
    "users-edit": ("Edit User", [
        "Update account details, role assignments, and directory status for the selected enterprise user.",
    ]),
    "user-detail": ("User Details", [
        "Read-only profile verification and security descriptors for this enterprise directory identity.",
    ]),

    # maintenance
    "asset-inspection-register": ("Asset Inspection Register", [
        "The log of all asset inspections performed, scheduled, and pending.",
    ]),
    "assigned-work-orders": ("Assigned Work Orders", [
        "Work orders assigned to technicians for repair or maintenance.",
    ]),
    "breakdown-register": ("Breakdown Register", [
        "Reported equipment and asset breakdowns awaiting or under repair.",
    ]),
    "pm-schedule": ("Preventive Maintenance Schedule", [
        "Scheduled recurring maintenance for assets, based on time or usage intervals.",
    ]),
    "service-evidence": ("Service Evidence Repository", [
        "Photos, videos, and documents attached to a work order's asset.",
    ]),
    "technician-dashboard": ("Technician Dashboard", [
        "Your assigned work orders, inspections, and breakdowns.",
    ]),
    "work-order-detail": ("Work Order Details", [
        "Full detail view for a single work order — assigned technician, status, and linked asset.",
    ]),
    "asset-inspection-detail": ("Asset Inspection Details", [
        "Full detail view for a single asset inspection record.",
    ]),
    "pm-schedule-detail": ("PM Schedule Details", [
        "Full detail view for a single preventive maintenance schedule entry.",
    ]),
    "breakdown-detail": ("Breakdown Details", [
        "Full detail view for a single reported breakdown.",
    ]),

    # organisation
    "hrms-sync": ("Directory Sync", [
        "Bring your departments and people in automatically from your HR and identity systems, instead of adding them by hand.",
        "Turn a source on and enter its details in Settings, then run a sync here.",
    ]),
    "org-units-assign": ("Approval Delegation Matrix", [
        "Delegate approval authority to a role within an org unit, with an optional monetary limit.",
    ]),
    "org-units": ("Organisation Units Master", [
        "Manage the organisation's department and unit hierarchy — create, edit, and organise every unit from here.",
    ]),
    "org-units-add": ("Add New Organisation Unit", [
        "Create a new department, division, or other organisational unit and place it in the hierarchy.",
    ]),
    "org-units-hierarchy": ("Company Hierarchy Visualizer", [
        "Visual tree of how every organisation unit relates to the others.",
    ]),
    "org-unit-detail": ("Organisation Unit Details", [
        "Full detail view for a single organisation unit — its type, parent, and members.",
    ]),

    # assets
    "asset-appreciation": ("Asset Appreciation", [
        "Record capital appreciation for asset classes expected to gain value over time, such as Land or Investment Property.",
        "Uses the same revaluation record as Asset Revaluation, restricted to upward moves.",
    ]),
    "asset-creation-queue": ("Asset Creation Queue", [
        "Convert real stock-in receipts into formalized asset entries.",
    ]),
    "disposal-approvals": ("Asset Disposal Queue", [
        "Assets pending decommission approval, and disposal history.",
    ]),
    "asset-register": ("Asset Register", [
        "The master list of every tracked asset in the organization, with lifecycle state, location, and quick actions.",
    ]),
    "asset-revaluation": ("Asset Revaluation", [
        "Adjust the recognized balances of physical assets in compliance with IAS 16 guidelines.",
    ]),
    "asset-detail": ("Asset Details", [
        "Full detail view for a single asset — specifications, custody, documents, financials, and history, across tabs.",
    ]),
    "assets-create": ("Create / Edit Asset", [
        "Register a new asset or edit an existing one — classification, specifications, location, and initial custody.",
    ]),

    # small misc modules
    "ai-copilot": ("AI Copilot", [
        "Your intelligent assistant for asset management — read-only.",
    ]),
    "document-dashboard": ("Document Intelligence", [
        "OCR coverage across the register, and SharePoint sync status.",
    ]),
    "document-repository": ("Document Repository Search", [
        "Full-text search across every document in the register.",
        "Results are scoped to your organisational unit.",
    ]),
    "expiry-renewal": ("Document Expiry & Retention", [
        "Alerts already raised by the expiry checker, and documents past their retention window awaiting action.",
    ]),
    "geo-workspace": ("Geo Workspace", [
        "GPS reference points, geofences, and spatial asset queries.",
        "A single asset's own position lives on its Location tab.",
    ]),
    "help": ("AAMS Help Center", [
        "System guidelines, workflows and step-by-step guides for every module.",
    ]),
    "hr-exit-processing": ("HR Exit Processing", [
        "Orphan custody assignments for departing employees and track assets awaiting interim custodian acceptance.",
    ]),
    "label-workspace": ("Label Workspace", [
        "Print templates, bulk label generation, the unmapped label pool, and coverage stats.",
        "Assigning a label to a specific asset lives on that asset's Labels tab.",
    ]),
    "notifications": ("Notification Center", [
        "Inbox, channel opt-in/out preferences, and safety-alert admin tools.",
    ]),
    "dynamic-fields": ("Dynamic Fields & Forms", [
        "Custom fields per module, validation rules, form layouts, and value bulk import.",
    ]),
    "feature-flags": ("Feature Flags & Module Management", [
        "Microservice modules, feature flags with gradual rollout, tenant overrides, and service health.",
    ]),
    "platform-admin": ("Platform Administration", [
        "Tenant provisioning and live system health.",
    ]),
    "system-configuration": ("System Configuration", [
        "System parameters, feature toggles, and lookup code masters.",
    ]),
    "asset-verification": ("Asset Verification", [
        "Asset registry and tag/RFID-based physical verification.",
    ]),
    "tag-management": ("Tag Management", [
        "Manage the QR / barcode / RFID tags on your assets.",
        "Create tags for many assets at once, find assets that have moved from where they should be, and verify tags.",
    ]),
    "verification-cycles": ("Verification Cycles", [
        "Physical asset verification cycles.",
        "Open a cycle for the full workflow.",
    ]),
    "tickets": ("Support Tickets", [
        "Manage all support requests, incidents, and change tickets.",
    ]),
    "user-profile": ("My Profile", [
        "Your personal profile, employee details, and account security settings.",
    ]),
    "workflow-approvals": ("Workflow Approvals", [
        "Pending approvals, instance history, delegated authority, and SLA performance.",
    ]),
    "workflow-templates": ("Workflow Templates", [
        "Define approval chains — steps, approvers, and SLAs — per module/trigger event.",
    ]),
}


def build_source_text() -> dict:
    source_text = {}
    for page_key, (title, body) in PAGES.items():
        source_text[f"{page_key}.title"] = title
        for i, paragraph in enumerate(body):
            source_text[f"{page_key}.body.{i}"] = paragraph
    return source_text


async def seed_translation_keys(session: AsyncSession, source_text: dict) -> int:
    inserted = 0
    now = datetime.now(timezone.utc)
    for key, text_value in source_text.items():
        existing = (await session.execute(
            text("SELECT id FROM translation_keys WHERE namespace = :ns AND key = :key"),
            {"ns": NAMESPACE, "key": key},
        )).scalar_one_or_none()
        if existing:
            await session.execute(
                text("UPDATE translation_keys SET source_text = :src WHERE id = :id"),
                {"src": text_value, "id": existing},
            )
        else:
            await session.execute(
                text("""INSERT INTO translation_keys (id, namespace, key, source_text, created_at)
                        VALUES (:id, :ns, :key, :src, :now)"""),
                {"id": str(uuid.uuid4()), "ns": NAMESPACE, "key": key, "src": text_value, "now": now},
            )
            inserted += 1
    await session.commit()
    return inserted


async def main() -> None:
    source_text = build_source_text()
    engine = create_async_engine(settings.DATABASE_URL, echo=False)
    Session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    async with Session() as session:
        tenants = (await session.execute(
            text("SELECT id::text AS id, slug FROM public.tenants WHERE status != 'archived'")
        )).fetchall()

    for tenant in tenants:
        schema = f"tenant_{tenant.id.replace('-', '_')}"
        async with Session() as session:
            await session.execute(text(f"SET search_path TO {schema}, public"))
            try:
                inserted = await seed_translation_keys(session, source_text)
                print(f"  seeded {inserted} new help keys ({len(source_text)} total): {tenant.slug}")
            except Exception as exc:
                print(f"  SKIPPED {tenant.slug}: {exc}")
                await session.rollback()

    await engine.dispose()
    print(f"Done — {len(tenants)} tenant(s) processed, {len(PAGES)} pages / {len(source_text)} keys.")


if __name__ == "__main__":
    asyncio.run(main())
