"""Tenant-side datasources and every form of the FleetSecure GRC app, with 10
sample records each — from the Tenant mockups (departments, roles, fleets,
users, KPIs, SOA and audits) plus Core's tenant onboarding wizard.

Form fields are FormFieldDef dicts; `lookup(..., "x")` names a datasource by
key, resolved when the build creates the form. Layout markers (wizard steps,
rows/columns, sections) are fields too — see frontend/src/lib/formLayout.ts.
"""

from .model_core import ACTIVE, R, boolean, date, num, ref, sel, status, txt

# ---- Tenant datasources -------------------------------------------------------------

TENANT = [
    {
        "key": "department", "name": "Department", "noun": "Department", "search": "Search departments…",
        "fields": [
            txt("department_name", "Name", True), txt("code", "Code", True, 20, True), ref("parent_department", "Parent", "self", "department_name"),
            txt("department_head", "Head"), txt("location", "Location"), status(),
        ],
        "rows": [
            {"_k": "CORP", "department_name": "Corporate", "code": "CORP", "department_head": "Hamad Al-Thani", "location": "Doha HQ", "status": "Active"},
            {"_k": "IT", "department_name": "Information Technology", "code": "IT", "parent_department": R("department", "CORP"), "department_head": "Karthik Raman", "location": "Doha HQ", "status": "Active"},
            {"_k": "OPS", "department_name": "Operations", "code": "OPS", "parent_department": R("department", "CORP"), "department_head": "Ian McLeod", "location": "Doha HQ", "status": "Active"},
            {"_k": "HSE", "department_name": "Health, Safety & Environment", "code": "HSE", "parent_department": R("department", "OPS"), "department_head": "James Okafor", "location": "Ras Laffan", "status": "Active"},
            {"_k": "DRILL", "department_name": "Drilling Operations", "code": "DRILL", "parent_department": R("department", "OPS"), "department_head": "Arjun Nair", "location": "Offshore", "status": "Active"},
            {"_k": "MARINE", "department_name": "Marine", "code": "MARINE", "parent_department": R("department", "OPS"), "department_head": "Captain Erik Dahl", "location": "Ras Laffan", "status": "Active"},
            {"_k": "OTSEC", "department_name": "OT Security", "code": "OTSEC", "parent_department": R("department", "IT"), "department_head": "Sara Haddad", "location": "Doha HQ", "status": "Active"},
            {"_k": "COMP", "department_name": "Compliance & Audit", "code": "COMP", "parent_department": R("department", "CORP"), "department_head": "Michael Rodriguez", "location": "Doha HQ", "status": "Active"},
            {"_k": "FIN", "department_name": "Finance", "code": "FIN", "parent_department": R("department", "CORP"), "department_head": "Nadia Khan", "location": "Doha HQ", "status": "Active"},
            {"_k": "SUPPLY", "department_name": "Supply Chain", "code": "SCM", "parent_department": R("department", "OPS"), "department_head": "Rafael Ortiz", "location": "Mesaieed", "status": "Inactive"},
        ],
    },
    {
        "key": "tenant_role", "name": "Tenant Role", "noun": "Role", "search": "Search roles…",
        "fields": [txt("code", "Code", True, 30, True), txt("role_name", "Name", True), txt("description", "Description"), status()],
        "rows": [
            {"_k": "SECMGR", "code": "SEC-MGR", "role_name": "Security Manager", "description": "Owns information security policy, control implementation and SOA applicability decisions.", "status": "Active"},
            {"_k": "GRCADMIN", "code": "GRC-ADMIN", "role_name": "GRC Administrator", "description": "Administers tenant GRC configuration, frameworks, users and published SOA revisions.", "status": "Active"},
            {"_k": "RISKOWNER", "code": "RISK-OWNER", "role_name": "Risk Owner", "description": "Accountable for risks and their treatment plans.", "status": "Active"},
            {"_k": "REVIEWER", "code": "REVIEWER", "role_name": "Reviewer", "description": "Reviews and approves KPI results and findings.", "status": "Active"},
            {"_k": "AUDITOR", "code": "INT-AUDITOR", "role_name": "Internal Auditor", "description": "Plans and performs internal audits.", "status": "Active"},
            {"_k": "LEAD", "code": "LEAD-AUDITOR", "role_name": "Lead Auditor", "description": "Leads audits and signs off assessments.", "status": "Active"},
            {"_k": "CTRLOWNER", "code": "CTRL-OWNER", "role_name": "Control Owner", "description": "Operates controls and submits KPI results.", "status": "Active"},
            {"_k": "ASSETMGR", "code": "ASSET-MGR", "role_name": "Asset Manager", "description": "Maintains fleets, rigs and asset registers.", "status": "Active"},
            {"_k": "EXEC", "code": "EXEC", "role_name": "Executive Viewer", "description": "Read-only dashboards for leadership.", "status": "Active"},
            {"_k": "CONTRACTOR", "code": "CONTRACTOR", "role_name": "Contractor", "description": "Limited access for third-party staff.", "status": "Inactive"},
        ],
    },
    {
        "key": "role_permission", "name": "Role Permission", "noun": "Permission", "search": "Search features...",
        "fields": [
            ref("role", "Role", "tenant_role", "role_name", req=True), ref("module", "Module", "module", "module_name", req=True),
            ref("feature", "Feature", "feature", "feature_name", req=True), boolean("can_view", "View"), boolean("can_add", "Add"),
            boolean("can_edit", "Edit"), boolean("can_delete", "Delete"), boolean("can_approve", "Approve"),
        ],
        "rows": [
            {"role": R("tenant_role", "SECMGR"), "module": R("module", "CONTROL"), "feature": R("feature", "LIBRARY"), "can_view": True, "can_add": True, "can_edit": True, "can_delete": False, "can_approve": True},
            {"role": R("tenant_role", "SECMGR"), "module": R("module", "RISK"), "feature": R("feature", "REGISTER"), "can_view": True, "can_add": True, "can_edit": True, "can_delete": False, "can_approve": False},
            {"role": R("tenant_role", "SECMGR"), "module": R("module", "RISK"), "feature": R("feature", "REVIEW"), "can_view": True, "can_add": False, "can_edit": True, "can_delete": False, "can_approve": True},
            {"role": R("tenant_role", "GRCADMIN"), "module": R("module", "SOA"), "feature": R("feature", "SOA"), "can_view": True, "can_add": True, "can_edit": True, "can_delete": True, "can_approve": True},
            {"role": R("tenant_role", "GRCADMIN"), "module": R("module", "FLEET"), "feature": R("feature", "FLEET"), "can_view": True, "can_add": True, "can_edit": True, "can_delete": True, "can_approve": False},
            {"role": R("tenant_role", "AUDITOR"), "module": R("module", "AUDIT"), "feature": R("feature", "PLAN"), "can_view": True, "can_add": True, "can_edit": True, "can_delete": False, "can_approve": False},
            {"role": R("tenant_role", "LEAD"), "module": R("module", "AUDIT"), "feature": R("feature", "FINDINGS"), "can_view": True, "can_add": True, "can_edit": True, "can_delete": False, "can_approve": True},
            {"role": R("tenant_role", "CTRLOWNER"), "module": R("module", "CONTROL"), "feature": R("feature", "KPI"), "can_view": True, "can_add": True, "can_edit": False, "can_delete": False, "can_approve": False},
            {"role": R("tenant_role", "REVIEWER"), "module": R("module", "CONTROL"), "feature": R("feature", "KPI"), "can_view": True, "can_add": False, "can_edit": True, "can_delete": False, "can_approve": True},
            {"role": R("tenant_role", "EXEC"), "module": R("module", "RISK"), "feature": R("feature", "HEAT"), "can_view": True, "can_add": False, "can_edit": False, "can_delete": False, "can_approve": False},
        ],
    },
    {
        "key": "unit", "name": "Fleet Unit", "noun": "Unit", "search": "Search fleets...",
        "fields": [
            ref("unit_type", "Unit Type", "unit_type", "unit_type_name", req=True), ref("parent_unit", "Parent Unit", "self", "unit_name"),
            txt("unit_code", "Code", True, 30, True), txt("unit_name", "Name", True), txt("operating_region", "Operating Region"),
            txt("location", "Location"), txt("description", "Description"), status(["Active", "Inactive", "Maintenance"]),
        ],
        "rows": [
            {"_k": "F1", "unit_type": R("unit_type", "FLEET"), "unit_code": "FLEET-01", "unit_name": "BlueCrest Americas Fleet", "operating_region": "Gulf of Mexico", "location": "Houston", "description": "Jack-ups and semi-submersibles in the Americas.", "status": "Active"},
            {"_k": "F3", "unit_type": R("unit_type", "FLEET"), "unit_code": "FLEET-03", "unit_name": "BlueCrest Middle East Fleet", "operating_region": "Arabian Gulf", "location": "Doha", "description": "Shallow-water jack-ups for GCC operators.", "status": "Active"},
            {"_k": "F4", "unit_type": R("unit_type", "FLEET"), "unit_code": "FLEET-04", "unit_name": "BlueCrest North Sea Fleet", "operating_region": "North Sea", "location": "Aberdeen", "description": "Harsh-environment semi-submersibles.", "status": "Active"},
            {"_k": "R101", "unit_type": R("unit_type", "RIG"), "parent_unit": R("unit", "F1"), "unit_code": "RIG-101", "unit_name": "BlueCrest Pioneer", "operating_region": "Gulf of Mexico", "location": "Block GC-640", "description": "Ultra-deepwater drillship.", "status": "Inactive"},
            {"_k": "R102", "unit_type": R("unit_type", "RIG"), "parent_unit": R("unit", "F1"), "unit_code": "RIG-102", "unit_name": "BlueCrest Mariner", "operating_region": "Gulf of Mexico", "location": "Block MC-252", "description": "Sixth-generation semi-submersible.", "status": "Active"},
            {"_k": "R103", "unit_type": R("unit_type", "RIG"), "parent_unit": R("unit", "F1"), "unit_code": "RIG-103", "unit_name": "ARIG-02", "operating_region": "Gulf of Mexico", "location": "Block GB-387", "description": "Jack-up working shallow shelf wells.", "status": "Active"},
            {"_k": "R104", "unit_type": R("unit_type", "RIG"), "parent_unit": R("unit", "F3"), "unit_code": "RIG-104", "unit_name": "BlueCrest Voyager", "operating_region": "Arabian Gulf", "location": "North Field", "description": "High-spec jack-up.", "status": "Active"},
            {"_k": "R105", "unit_type": R("unit_type", "RIG"), "parent_unit": R("unit", "F3"), "unit_code": "RIG-105", "unit_name": "BlueCrest Explorer", "operating_region": "Arabian Gulf", "location": "Al Shaheen", "description": "Jack-up in planned maintenance.", "status": "Maintenance"},
            {"_k": "R106", "unit_type": R("unit_type", "RIG"), "parent_unit": R("unit", "F4"), "unit_code": "RIG-106", "unit_name": "BlueCrest Highlander", "operating_region": "North Sea", "location": "Quad 9", "description": "Harsh-environment semi-submersible.", "status": "Active"},
            {"_k": "Z1", "unit_type": R("unit_type", "ZONE"), "parent_unit": R("unit", "R102"), "unit_code": "ZONE-102-A", "unit_name": "Mariner Drill Floor Zone", "operating_region": "Gulf of Mexico", "location": "Drill floor", "description": "OT zone for drilling control systems.", "status": "Active"},
        ],
    },
    {
        "key": "unit_asset", "name": "Unit Asset", "noun": "Asset", "search": "Search assets...",
        "fields": [
            ref("unit", "Unit", "unit", "unit_name", req=True), txt("asset_name", "Asset", True), txt("asset_code", "Code", True, 30),
            ref("asset_type", "Type", "asset_type", "asset_type_name"), txt("location", "Location"), status(["Active", "Maintenance", "Retired"]),
        ],
        "rows": [
            {"unit": R("unit", "R101"), "asset_name": "Top Drive TD-450", "asset_code": "AST-101-01", "asset_type": R("asset_type", "DRILL"), "location": "Drill floor", "status": "Active"},
            {"unit": R("unit", "R101"), "asset_name": "Mud Pump MP-2200", "asset_code": "AST-101-02", "asset_type": R("asset_type", "PUMP"), "location": "Mud pump room", "status": "Active"},
            {"unit": R("unit", "R101"), "asset_name": "BOP Stack 18-3/4\"", "asset_code": "AST-101-03", "asset_type": R("asset_type", "WELLCTL"), "location": "Moon pool", "status": "Maintenance"},
            {"unit": R("unit", "R102"), "asset_name": "Drawworks DW-3000", "asset_code": "AST-102-01", "asset_type": R("asset_type", "DRILL"), "location": "Drill floor", "status": "Active"},
            {"unit": R("unit", "R102"), "asset_name": "Drilling Control Network", "asset_code": "AST-102-02", "asset_type": R("asset_type", "OTNET"), "location": "Driller's cabin", "status": "Active"},
            {"unit": R("unit", "R103"), "asset_name": "Choke Manifold CM-15K", "asset_code": "AST-103-01", "asset_type": R("asset_type", "WELLCTL"), "location": "Cellar deck", "status": "Active"},
            {"unit": R("unit", "R104"), "asset_name": "Pedestal Crane PC-60", "asset_code": "AST-104-01", "asset_type": R("asset_type", "CRANE"), "location": "Main deck", "status": "Active"},
            {"unit": R("unit", "R105"), "asset_name": "Mud Pump MP-1600", "asset_code": "AST-105-01", "asset_type": R("asset_type", "PUMP"), "location": "Mud pump room", "status": "Maintenance"},
            {"unit": R("unit", "R106"), "asset_name": "Ballast Control System", "asset_code": "AST-106-01", "asset_type": R("asset_type", "OTNET"), "location": "Control room", "status": "Active"},
            {"unit": R("unit", "R106"), "asset_name": "Legacy Top Drive TD-250", "asset_code": "AST-106-02", "asset_type": R("asset_type", "DRILL"), "location": "Warehouse", "status": "Retired"},
        ],
    },
    {
        "key": "tenant_user", "name": "Tenant User", "noun": "User", "search": "Search users…",
        "fields": [
            txt("full_name", "User", True, indexed=True), txt("work_email", "Email", True, 160), txt("employee_id", "Employee ID", True, 30), txt("phone", "Phone", True, 30),
            ref("primary_unit", "Primary Unit", "unit", "unit_name"),
            sel("operational_role", "Primary Operational Role", ["HSE Manager", "Safety Officer", "Rig Manager", "Compliance Lead", "Internal Auditor", "Asset Manager", "IT Security Lead", "Operations Superintendent", "Marine Superintendent", "Training Coordinator"]),
            ref("app_roles", "App Roles", "tenant_role", "role_name", multi=True), txt("hierarchy_scope", "Hierarchy Scope"),
            status(["Active", "Invited", "Inactive"]),
        ],
        "rows": [
            {"_k": "JO", "full_name": "James Okafor", "work_email": "james.okafor@bluecrest.example", "employee_id": "BC-0102", "phone": "+974 5511 2200", "operational_role": "HSE Manager", "app_roles": [R("tenant_role", "RISKOWNER"), R("tenant_role", "REVIEWER")], "hierarchy_scope": "Organisation (all units)", "status": "Active"},
            {"_k": "PR", "full_name": "Priya Raman", "work_email": "priya.raman@bluecrest.example", "employee_id": "BC-0417", "phone": "+974 5522 1188", "primary_unit": R("unit", "R103"), "operational_role": "Safety Officer", "app_roles": [R("tenant_role", "AUDITOR")], "hierarchy_scope": "Americas Fleet + sub-units", "status": "Active"},
            {"_k": "MR", "full_name": "Michael Rodriguez", "work_email": "michael.rodriguez@bluecrest.example", "employee_id": "BC-0233", "phone": "+974 5533 4410", "operational_role": "Internal Auditor", "app_roles": [R("tenant_role", "LEAD")], "hierarchy_scope": "Organisation (all units)", "status": "Active"},
            {"_k": "SC", "full_name": "Sarah Chen", "work_email": "sarah.chen@bluecrest.example", "employee_id": "BC-0288", "phone": "+974 5533 9021", "primary_unit": R("unit", "F1"), "operational_role": "Compliance Lead", "app_roles": [R("tenant_role", "AUDITOR"), R("tenant_role", "SECMGR")], "hierarchy_scope": "Americas Fleet + sub-units", "status": "Active"},
            {"_k": "DK", "full_name": "David Kim", "work_email": "david.kim@bluecrest.example", "employee_id": "BC-0315", "phone": "+974 5544 1200", "primary_unit": R("unit", "R102"), "operational_role": "IT Security Lead", "app_roles": [R("tenant_role", "CTRLOWNER")], "hierarchy_scope": "BlueCrest Mariner", "status": "Active"},
            {"_k": "RC", "full_name": "Rachel Chen", "work_email": "rachel.chen@bluecrest.example", "employee_id": "BC-0351", "phone": "+974 5544 7788", "primary_unit": R("unit", "F3"), "operational_role": "Operations Superintendent", "app_roles": [R("tenant_role", "AUDITOR")], "hierarchy_scope": "Middle East Fleet + sub-units", "status": "Active"},
            {"_k": "SP", "full_name": "Sanjay Patel", "work_email": "sanjay.patel@bluecrest.example", "employee_id": "BC-0390", "phone": "+974 5555 3021", "primary_unit": R("unit", "R104"), "operational_role": "Rig Manager", "app_roles": [R("tenant_role", "CTRLOWNER"), R("tenant_role", "ASSETMGR")], "hierarchy_scope": "BlueCrest Voyager", "status": "Active"},
            {"_k": "ED", "full_name": "Erik Dahl", "work_email": "erik.dahl@bluecrest.example", "employee_id": "BC-0402", "phone": "+47 912 44 556", "primary_unit": R("unit", "F4"), "operational_role": "Marine Superintendent", "app_roles": [R("tenant_role", "ASSETMGR")], "hierarchy_scope": "North Sea Fleet + sub-units", "status": "Active"},
            {"_k": "NK", "full_name": "Nadia Khan", "work_email": "nadia.khan@bluecrest.example", "employee_id": "BC-0455", "phone": "+974 5566 8890", "operational_role": "Training Coordinator", "app_roles": [R("tenant_role", "EXEC")], "hierarchy_scope": "Organisation (all units)", "status": "Invited"},
            {"_k": "RO", "full_name": "Rafael Ortiz", "work_email": "rafael.ortiz@bluecrest.example", "employee_id": "BC-0471", "phone": "+974 5577 1234", "primary_unit": R("unit", "R105"), "operational_role": "Asset Manager", "app_roles": [R("tenant_role", "CONTRACTOR")], "hierarchy_scope": "BlueCrest Explorer", "status": "Inactive"},
        ],
    },
    {
        "key": "audit_scoring_head", "name": "Audit Scoring Head", "noun": "Scoring Head", "search": "Search scoring heads...",
        "fields": [txt("head_name", "Scoring Head", True), num("weight", "Weight", True, "numeric"), num("display_order", "Order"), txt("description", "Description"), status()],
        "rows": [
            {"head_name": "Design Effectiveness", "weight": 1, "display_order": 1, "description": "Is the control designed to meet its objective?", "status": "Active"},
            {"head_name": "Operational Effectiveness", "weight": 1, "display_order": 2, "description": "Did the control operate as designed through the period?", "status": "Active"},
            {"head_name": "Documentation Quality", "weight": 0.5, "display_order": 3, "description": "Procedures are current, approved and accessible.", "status": "Active"},
            {"head_name": "Evidence Sufficiency", "weight": 0.75, "display_order": 4, "description": "Evidence is complete, dated and attributable.", "status": "Active"},
            {"head_name": "Timeliness", "weight": 0.5, "display_order": 5, "description": "Activities happen at the defined frequency.", "status": "Active"},
            {"head_name": "Control Ownership", "weight": 0.5, "display_order": 6, "description": "A named owner is accountable.", "status": "Active"},
            {"head_name": "Testing Coverage", "weight": 0.75, "display_order": 7, "description": "Sample covers the population and period.", "status": "Active"},
            {"head_name": "Remediation Effectiveness", "weight": 0.75, "display_order": 8, "description": "Earlier findings were closed effectively.", "status": "Active"},
            {"head_name": "Monitoring", "weight": 0.5, "display_order": 9, "description": "Exceptions are monitored and escalated.", "status": "Active"},
            {"head_name": "Training & Awareness", "weight": 0.25, "display_order": 10, "description": "Operators are trained on the control.", "status": "Inactive"},
        ],
    },
    {
        "key": "audit_rating_level", "name": "Audit Rating Level", "noun": "Rating Level", "search": "Search rating levels...",
        "fields": [
            sel("scale", "Scale", ["Standard", "Maturity"], req=True), num("display_order", "Order", True), txt("label", "Label", True, 40),
            txt("value", "Value", True, 10), txt("colour", "Colour", max_length=9), status(),
        ],
        "rows": [
            {"scale": "Standard", "display_order": 1, "label": "Poor", "value": "1", "colour": "#ef4444", "status": "Active"},
            {"scale": "Standard", "display_order": 2, "label": "Fair", "value": "2", "colour": "#f59e0b", "status": "Active"},
            {"scale": "Standard", "display_order": 3, "label": "Good", "value": "3", "colour": "#84cc16", "status": "Active"},
            {"scale": "Standard", "display_order": 4, "label": "Very good", "value": "4", "colour": "#22c55e", "status": "Active"},
            {"scale": "Standard", "display_order": 5, "label": "Excellent", "value": "5", "colour": "#15803d", "status": "Active"},
            {"scale": "Maturity", "display_order": 1, "label": "Not achieved", "value": "NA", "colour": "#ef4444", "status": "Active"},
            {"scale": "Maturity", "display_order": 2, "label": "Partially achieved", "value": "PA", "colour": "#f59e0b", "status": "Active"},
            {"scale": "Maturity", "display_order": 3, "label": "Largely achieved", "value": "LA", "colour": "#84cc16", "status": "Active"},
            {"scale": "Maturity", "display_order": 4, "label": "Fully achieved", "value": "FA", "colour": "#15803d", "status": "Active"},
            {"scale": "Maturity", "display_order": 5, "label": "Not assessed", "value": "N/A", "colour": "#94a3b8", "status": "Inactive"},
        ],
    },
    {
        "key": "audit_setting", "name": "Audit Setting", "noun": "Audit Profile", "search": "Search audit profiles...",
        "fields": [
            txt("profile_name", "Profile", True), sel("audit_type", "Audit Type", ["Internal Audit", "External Audit", "Shareholder Audit", "Regulator Audit", "Review Activity"], req=True),
            sel("composition_rule", "Composition Rule", ["Unweighted average of all heads", "Weighted average of all heads"], req=True),
            num("auto_approved_extensions", "Auto-approved extensions before escalation"),
            sel("escalated_approver", "Escalated extension approver", ["Department Owner", "Reviewer / Approver", "Executive Committee"], req=True),
            boolean("require_independent_validation", "Validation by a different user than the implementer"), status(),
        ],
        "rows": [
            {"profile_name": "Internal — organisational", "audit_type": "Internal Audit", "composition_rule": "Unweighted average of all heads", "auto_approved_extensions": 1, "escalated_approver": "Department Owner", "require_independent_validation": True, "status": "Active"},
            {"profile_name": "Internal — unit level", "audit_type": "Internal Audit", "composition_rule": "Weighted average of all heads", "auto_approved_extensions": 2, "escalated_approver": "Department Owner", "require_independent_validation": True, "status": "Active"},
            {"profile_name": "External certification", "audit_type": "External Audit", "composition_rule": "Weighted average of all heads", "auto_approved_extensions": 0, "escalated_approver": "Executive Committee", "require_independent_validation": True, "status": "Active"},
            {"profile_name": "External surveillance", "audit_type": "External Audit", "composition_rule": "Unweighted average of all heads", "auto_approved_extensions": 1, "escalated_approver": "Reviewer / Approver", "require_independent_validation": True, "status": "Active"},
            {"profile_name": "Shareholder review", "audit_type": "Shareholder Audit", "composition_rule": "Weighted average of all heads", "auto_approved_extensions": 0, "escalated_approver": "Executive Committee", "require_independent_validation": True, "status": "Active"},
            {"profile_name": "Regulator inspection", "audit_type": "Regulator Audit", "composition_rule": "Weighted average of all heads", "auto_approved_extensions": 0, "escalated_approver": "Executive Committee", "require_independent_validation": True, "status": "Active"},
            {"profile_name": "Flag-state survey", "audit_type": "Regulator Audit", "composition_rule": "Unweighted average of all heads", "auto_approved_extensions": 1, "escalated_approver": "Reviewer / Approver", "require_independent_validation": False, "status": "Active"},
            {"profile_name": "Quarterly review activity", "audit_type": "Review Activity", "composition_rule": "Unweighted average of all heads", "auto_approved_extensions": 3, "escalated_approver": "Reviewer / Approver", "require_independent_validation": False, "status": "Active"},
            {"profile_name": "Management walk-through", "audit_type": "Review Activity", "composition_rule": "Unweighted average of all heads", "auto_approved_extensions": 2, "escalated_approver": "Department Owner", "require_independent_validation": False, "status": "Active"},
            {"profile_name": "Legacy scoring (2024)", "audit_type": "Internal Audit", "composition_rule": "Unweighted average of all heads", "auto_approved_extensions": 2, "escalated_approver": "Department Owner", "require_independent_validation": False, "status": "Inactive"},
        ],
    },
]

# ---- Forms --------------------------------------------------------------------------


def ff(name, label, type="text", req=False, **kw):
    f = {"name": name, "type": type, "label": label, "required": req, "visibility_rules": []}
    f.update(kw)
    return f


def lookup(name, label, target, display, req=False, **kw):
    return ff(name, label, "lookup", req, _master=target, master_display_field=display, **kw)


def marker(kind, label, name):
    return ff(name, label, kind)


def columns(left, right, tag):
    """Two side-by-side columns (a row with two column markers)."""
    return [marker("row", "", f"row_{tag}"), marker("column", "", f"col_{tag}_1"), *left, marker("column", "", f"col_{tag}_2"), *right, marker("group_end", "", f"end_{tag}")]


FORMS = [
    {
        "key": "client_tenant", "name": "Client Tenant", "group": "core",
        "fields": [
            marker("wizard", "Company Profile", "step_profile"),
            *columns(
                [ff("legal_company_name", "Legal Company Name", req=True, placeholder="e.g., BlueCrest Drilling Co. W.L.L."), ff("display_name", "Display Name", placeholder="e.g., BlueCrest Drilling"), ff("tenant_code", "Tenant Code", req=True, placeholder="e.g., BLUECREST"), lookup("industry", "Industry", "industry", "industry_name", req=True)],
                [lookup("country", "Country", "country", "country_name", req=True), lookup("currency", "Currency", "currency", "code", req=True), lookup("time_zone", "Time Zone", "timezone", "time_zone_code", req=True)],
                "profile",
            ),
            marker("section", "Company Address", "sec_address"),
            *columns(
                [ff("address_line_1", "Address Line 1", req=True, placeholder="e.g., Building 12, West Bay"), ff("address_line_2", "Address Line 2", placeholder="e.g., Floor 3, Suite 301"), ff("city", "City", req=True, placeholder="e.g., Doha")],
                [ff("state", "State / Province", placeholder="e.g., Ad Dawhah"), ff("pin_zip", "PIN / ZIP", req=True, placeholder="e.g., 12345")],
                "address",
            ),
            marker("wizard", "Subscription", "step_subscription"),
            lookup("package", "Package", "package", "package_name", req=True),
            ff("billing_cycle", "Billing Cycle", "radio", True, options=["Monthly", "Annually"]),
            ff("licensed_users", "Licensed Users", "number", True, min=1),
            ff("subscription_start", "Subscription Start", "date", True),
            marker("wizard", "Deployment", "step_deployment"),
            ff("deployment", "Deployment", "radio", True, options=["SaaS — hosted by us", "Private cloud / on-premise"]),
            *columns(
                [ff("subdomain", "Subdomain", placeholder="e.g., bluecrest"), ff("region", "Region", "dropdown", options=["Middle East (me-central)", "Europe West (eu-west-1)", "Europe Central (eu-central-1)", "US East (us-east-1)", "US West (us-west-2)", "Asia Pacific South (ap-south-1)", "Asia Pacific SE (ap-southeast-1)"])],
                [ff("url", "URL", "url", placeholder="e.g., https://grc.yourcompany.com")],
                "deploy",
            ),
            marker("wizard", "Tenant Admin", "step_admin"),
            *columns(
                [ff("admin_full_name", "Full Name", req=True, placeholder="e.g., John Smith"), ff("admin_work_email", "Work Email", "email", True, placeholder="e.g., admin@company.com")],
                [ff("admin_phone", "Phone", placeholder="e.g., +1 234 567 8900"), ff("status", "Status", "dropdown", True, options=["Active", "Provisioning", "Suspended"], default_value="Provisioning")],
                "admin",
            ),
        ],
        "rows": [
            {"legal_company_name": "BlueCrest Drilling Co. W.L.L.", "display_name": "BlueCrest Drilling", "tenant_code": "BLUECREST", "industry": R("industry", "OG-DRL"), "country": R("country", "QA"), "currency": R("currency", "USD"), "time_zone": R("timezone", "Qatar"), "address_line_1": "Building 12, West Bay", "address_line_2": "Floor 3", "city": "Doha", "state": "Ad Dawhah", "pin_zip": "12345", "package": R("package", "RISK"), "billing_cycle": "Annually", "licensed_users": 100, "subscription_start": "2026-01-01", "deployment": "SaaS — hosted by us", "subdomain": "bluecrest", "region": "Middle East (me-central)", "url": "https://bluecrest.fleetsecuregrc.com", "admin_full_name": "Hamad Al-Thani", "admin_work_email": "bc.admin@bluecrest.example", "admin_phone": "+974 4400 1100", "status": "Active"},
            {"legal_company_name": "Nordic Offshore Services AS", "display_name": "Nordic Offshore", "tenant_code": "NORDICOFF", "industry": R("industry", "MAR-OSV"), "country": R("country", "NO"), "currency": R("currency", "NOK"), "time_zone": R("timezone", "Oslo"), "address_line_1": "Strandkaien 18", "city": "Stavanger", "pin_zip": "4005", "package": R("package", "MARINE"), "billing_cycle": "Annually", "licensed_users": 60, "subscription_start": "2026-03-01", "deployment": "SaaS — hosted by us", "subdomain": "nordicoffshore", "region": "Europe West (eu-west-1)", "url": "https://nordicoffshore.fleetsecuregrc.com", "admin_full_name": "Ingrid Solberg", "admin_work_email": "ingrid.solberg@nordicoffshore.example", "admin_phone": "+47 51 20 30 40", "status": "Active"},
            {"legal_company_name": "Gulf Pipeline Company LLC", "display_name": "Gulf Pipelines", "tenant_code": "GULFPIPE", "industry": R("industry", "MID-PIP"), "country": R("country", "AE"), "currency": R("currency", "AED"), "time_zone": R("timezone", "Dubai"), "address_line_1": "Tower B, Business Bay", "city": "Dubai", "pin_zip": "00000", "package": R("package", "PIPE"), "billing_cycle": "Monthly", "licensed_users": 50, "subscription_start": "2026-04-15", "deployment": "Private cloud / on-premise", "url": "https://grc.gulfpipelines.example", "admin_full_name": "Omar Saeed", "admin_work_email": "omar.saeed@gulfpipelines.example", "admin_phone": "+971 4 330 2200", "status": "Active"},
            {"legal_company_name": "Arabian Drilling Services", "display_name": "ArabDrill", "tenant_code": "ARABDRILL", "industry": R("industry", "OG-DRL"), "country": R("country", "SA"), "currency": R("currency", "SAR"), "time_zone": R("timezone", "Riyadh"), "address_line_1": "King Fahd Road", "city": "Dammam", "pin_zip": "32241", "package": R("package", "GULF"), "billing_cycle": "Annually", "licensed_users": 80, "subscription_start": "2026-05-01", "deployment": "SaaS — hosted by us", "subdomain": "arabdrill", "region": "Middle East (me-central)", "url": "https://arabdrill.fleetsecuregrc.com", "admin_full_name": "Faisal Al-Harbi", "admin_work_email": "f.harbi@arabdrill.example", "admin_phone": "+966 13 800 1122", "status": "Active"},
            {"legal_company_name": "Coastal Power Transmission Ltd", "display_name": "Coastal Power", "tenant_code": "COASTALPWR", "industry": R("industry", "PWR-TRN"), "country": R("country", "GB"), "currency": R("currency", "GBP"), "time_zone": R("timezone", "London"), "address_line_1": "1 Grid Way", "city": "Aberdeen", "pin_zip": "AB10 1AA", "package": R("package", "OT"), "billing_cycle": "Annually", "licensed_users": 40, "subscription_start": "2026-02-01", "deployment": "SaaS — hosted by us", "subdomain": "coastalpower", "region": "Europe West (eu-west-1)", "url": "https://coastalpower.fleetsecuregrc.com", "admin_full_name": "Fiona Grant", "admin_work_email": "fiona.grant@coastalpower.example", "admin_phone": "+44 1224 555 010", "status": "Active"},
            {"legal_company_name": "Lone Star Onshore Partners", "display_name": "Lone Star Onshore", "tenant_code": "LONESTAR", "industry": R("industry", "OG-ON"), "country": R("country", "US"), "currency": R("currency", "USD"), "time_zone": R("timezone", "NewYork"), "address_line_1": "800 Louisiana St", "city": "Houston", "state": "Texas", "pin_zip": "77002", "package": R("package", "HSE"), "billing_cycle": "Monthly", "licensed_users": 15, "subscription_start": "2026-06-01", "deployment": "SaaS — hosted by us", "subdomain": "lonestar", "region": "US East (us-east-1)", "url": "https://lonestar.fleetsecuregrc.com", "admin_full_name": "Cody Walker", "admin_work_email": "cody.walker@lonestar.example", "admin_phone": "+1 713 555 0142", "status": "Active"},
            {"legal_company_name": "Malabar Marine Terminals Pvt Ltd", "display_name": "Malabar Terminals", "tenant_code": "MALABAR", "industry": R("industry", "MAR-PRT"), "country": R("country", "IN"), "currency": R("currency", "INR"), "time_zone": R("timezone", "Kolkata"), "address_line_1": "Willingdon Island", "city": "Kochi", "state": "Kerala", "pin_zip": "682003", "package": R("package", "COMP"), "billing_cycle": "Annually", "licensed_users": 25, "subscription_start": "2026-07-01", "deployment": "SaaS — hosted by us", "subdomain": "malabar", "region": "Asia Pacific South (ap-south-1)", "url": "https://malabar.fleetsecuregrc.com", "admin_full_name": "Anil Varghese", "admin_work_email": "anil.varghese@malabar.example", "admin_phone": "+91 484 266 1000", "status": "Provisioning"},
            {"legal_company_name": "Straits Oilfield Services Pte Ltd", "display_name": "Straits OFS", "tenant_code": "STRAITSOFS", "industry": R("industry", "OFS-SVC"), "country": R("country", "SG"), "currency": R("currency", "SGD"), "time_zone": R("timezone", "Singapore"), "address_line_1": "10 Pioneer Road", "city": "Singapore", "pin_zip": "628475", "package": R("package", "AUDIT"), "billing_cycle": "Monthly", "licensed_users": 30, "subscription_start": "2026-08-01", "deployment": "SaaS — hosted by us", "subdomain": "straitsofs", "region": "Asia Pacific SE (ap-southeast-1)", "url": "https://straitsofs.fleetsecuregrc.com", "admin_full_name": "Wei Ling Tan", "admin_work_email": "weiling.tan@straitsofs.example", "admin_phone": "+65 6555 0199", "status": "Active"},
            {"legal_company_name": "Rheinland Chemie GmbH", "display_name": "Rheinland Chemie", "tenant_code": "RHEINCHEM", "industry": R("industry", "CHM-PET"), "country": R("country", "DE"), "currency": R("currency", "EUR"), "time_zone": R("timezone", "Berlin"), "address_line_1": "Industriestraße 4", "city": "Ludwigshafen", "pin_zip": "67059", "package": R("package", "ENT"), "billing_cycle": "Annually", "licensed_users": 200, "subscription_start": "2026-09-01", "deployment": "Private cloud / on-premise", "url": "https://grc.rheinchem.example", "admin_full_name": "Katrin Vogel", "admin_work_email": "katrin.vogel@rheinchem.example", "admin_phone": "+49 621 600 1000", "status": "Provisioning"},
            {"legal_company_name": "Desert Mining Corporation", "display_name": "Desert Mining", "tenant_code": "DESERTMIN", "industry": R("industry", "MIN-SFE"), "country": R("country", "SA"), "currency": R("currency", "SAR"), "time_zone": R("timezone", "Riyadh"), "address_line_1": "Ma'aden Road", "city": "Riyadh", "pin_zip": "11461", "package": R("package", "LEGACY"), "billing_cycle": "Monthly", "licensed_users": 10, "subscription_start": "2025-01-01", "deployment": "SaaS — hosted by us", "subdomain": "desertmining", "region": "Middle East (me-central)", "url": "https://desertmining.fleetsecuregrc.com", "admin_full_name": "Nasser Al-Qahtani", "admin_work_email": "nasser.q@desertmining.example", "admin_phone": "+966 11 400 2200", "status": "Suspended"},
        ],
    },
    {
        "key": "soa", "name": "Statement of Applicability", "group": "tenant",
        "fields": [
            marker("wizard", "Framework", "step_framework"),
            ff("soa_title", "SOA Title", req=True, placeholder="e.g., Organizational SOA — ISO 27001"),
            ff("scope", "Scope", "radio", True, options=["Organizational", "Fleet", "Rig"]),
            lookup("unit", "Applies To", "unit", "unit_name", visibility_rules=[{"driver_field": "scope", "operator": "not_equals", "value": "Organizational"}]),
            lookup("framework", "Framework", "framework", "framework_code", req=True),
            marker("wizard", "Version", "step_version"),
            lookup("framework_version", "Framework Version", "framework_version", "version_label", req=True),
            marker("wizard", "Configure Content", "step_content"),
            ff("applicability", "Applicability", "dropdown", True, options=["Applicable", "Partially applicable", "Not applicable"]),
            *columns(
                [ff("domains_in_scope", "Domains in Scope", "number", min=0), ff("controls_in_scope", "Controls in Scope", "number", min=0)],
                [ff("kpis_in_scope", "KPIs in Scope", "number", min=0), ff("excluded_controls", "Excluded Controls", "number", min=0)],
                "content",
            ),
            ff("justification", "Justification", "textarea", placeholder="Why these controls apply (or don't)…"),
            marker("wizard", "Preview", "step_preview"),
            *columns(
                [ff("revision", "Revision", req=True, placeholder="e.g., Rev 3"), ff("status", "Status", "dropdown", True, options=["Draft", "Published", "Superseded"], default_value="Draft")],
                [ff("published_on", "Published On", "date"), ff("owner", "SOA Owner")],
                "preview",
            ),
        ],
        "rows": [
            {"_k": "ORG-ISO", "soa_title": "Organizational SOA — ISO 27001", "scope": "Organizational", "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "applicability": "Applicable", "domains_in_scope": 4, "controls_in_scope": 93, "kpis_in_scope": 287, "excluded_controls": 3, "justification": "All Annex A controls apply to corporate and offshore operations except physical controls owned by the landlord.", "revision": "Rev 3", "status": "Published", "published_on": "2026-03-10", "owner": "Sarah Chen"},
            {"_k": "ORG-NIST", "soa_title": "Organizational SOA — NIST CSF", "scope": "Organizational", "framework": R("framework", "NIST"), "framework_version": R("framework_version", "NIST24"), "applicability": "Applicable", "domains_in_scope": 6, "controls_in_scope": 106, "kpis_in_scope": 64, "excluded_controls": 0, "justification": "Adopted alongside ISO 27001 for OT reporting.", "revision": "Rev 2", "status": "Published", "published_on": "2026-03-10", "owner": "Sarah Chen"},
            {"_k": "FLT1-ISO", "soa_title": "Americas Fleet SOA — ISO 27001", "scope": "Fleet", "unit": R("unit", "F1"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "applicability": "Partially applicable", "domains_in_scope": 3, "controls_in_scope": 72, "kpis_in_scope": 18, "excluded_controls": 21, "justification": "Fleet-level controls only; corporate controls inherited.", "revision": "Rev 1", "status": "Published", "published_on": "2026-05-02", "owner": "James Okafor"},
            {"_k": "FLT4-API", "soa_title": "North Sea Fleet SOA — API RP 75", "scope": "Fleet", "unit": R("unit", "F4"), "framework": R("framework", "APIRP75"), "framework_version": R("framework_version", "API19"), "applicability": "Applicable", "domains_in_scope": 1, "controls_in_scope": 2, "kpis_in_scope": 4, "excluded_controls": 0, "justification": "SEMS elements for harsh-environment operations.", "revision": "Rev 1", "status": "Published", "published_on": "2026-06-18", "owner": "Erik Dahl"},
            {"_k": "RIG102-ISA", "soa_title": "Mariner Rig SOA — ISA/IEC 62443-3-3", "scope": "Rig", "unit": R("unit", "R102"), "framework": R("framework", "ISA62443"), "framework_version": R("framework_version", "ISA13"), "applicability": "Applicable", "domains_in_scope": 7, "controls_in_scope": 51, "kpis_in_scope": 40, "excluded_controls": 0, "justification": "Drilling control network in scope for SL-2.", "revision": "Rev 2", "status": "Published", "published_on": "2026-07-01", "owner": "David Kim"},
            {"_k": "RIG101-ISA", "soa_title": "Pioneer Rig SOA — ISA/IEC 62443-3-3", "scope": "Rig", "unit": R("unit", "R101"), "framework": R("framework", "ISA62443"), "framework_version": R("framework_version", "ISA13"), "applicability": "Partially applicable", "domains_in_scope": 5, "controls_in_scope": 38, "kpis_in_scope": 22, "excluded_controls": 13, "justification": "Rig stacked; only remote-access controls in scope.", "revision": "Rev 1", "status": "Published", "published_on": "2026-06-20", "owner": "Priya Raman"},
            {"_k": "FLT3-ISO", "soa_title": "Middle East Fleet SOA — ISO 27001", "scope": "Fleet", "unit": R("unit", "F3"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "applicability": "Applicable", "domains_in_scope": 4, "controls_in_scope": 80, "kpis_in_scope": 30, "excluded_controls": 13, "justification": "GCC regulator expects full Annex A coverage.", "revision": "Rev 1", "status": "Draft", "owner": "Rachel Chen"},
            {"_k": "ORG-ISO45", "soa_title": "Organizational SOA — ISO 45001", "scope": "Organizational", "framework": R("framework", "ISO45001"), "framework_version": R("framework_version", "ISO45"), "applicability": "Applicable", "domains_in_scope": 9, "controls_in_scope": 48, "kpis_in_scope": 12, "excluded_controls": 0, "justification": "OH&S management system for all sites.", "revision": "Rev 1", "status": "Draft", "owner": "James Okafor"},
            {"_k": "RIG104-ISO", "soa_title": "Voyager Rig SOA — ISO 27001", "scope": "Rig", "unit": R("unit", "R104"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "applicability": "Partially applicable", "domains_in_scope": 2, "controls_in_scope": 41, "kpis_in_scope": 15, "excluded_controls": 52, "justification": "Rig-level technical controls only.", "revision": "Rev 1", "status": "Draft", "owner": "Sanjay Patel"},
            {"_k": "ORG-ISO13", "soa_title": "Organizational SOA — ISO 27001 (2013)", "scope": "Organizational", "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO13"), "applicability": "Applicable", "domains_in_scope": 14, "controls_in_scope": 114, "kpis_in_scope": 250, "excluded_controls": 0, "justification": "Superseded by the 2022 revision.", "revision": "Rev 2", "status": "Superseded", "published_on": "2024-01-15", "owner": "Sarah Chen"},
        ],
    },
    {
        "key": "kpi_assignment", "name": "KPI Assignment", "group": "tenant",
        "fields": [
            lookup("assignee", "User", "tenant_user", "full_name", req=True),
            ff("level", "Assignment Level", "radio", True, options=["Organisational", "Unit level"]),
            lookup("unit", "Unit", "unit", "unit_name", visibility_rules=[{"driver_field": "level", "operator": "equals", "value": "Unit level"}]),
            lookup("kpi", "KPI", "kpi", "kpi_title", req=True),
            *columns(
                [ff("frequency", "Frequency", "dropdown", True, options=["Hourly", "Monthly", "Annually"]), ff("every", "Every", "number", True, min=1, default_value="1")],
                [ff("start_date", "Start Date", "date", True), ff("status", "Status", "dropdown", True, options=["Active", "Paused"], default_value="Active")],
                "freq",
            ),
            ff("notes", "Notes", "textarea"),
        ],
        "rows": [
            {"assignee": R("tenant_user", "JO"), "level": "Organisational", "kpi": R("kpi", "K001"), "frequency": "Monthly", "every": 1, "start_date": "2026-01-01", "status": "Active", "notes": "Org-wide access review."},
            {"assignee": R("tenant_user", "JO"), "level": "Organisational", "kpi": R("kpi", "K003"), "frequency": "Annually", "every": 1, "start_date": "2026-01-01", "status": "Active"},
            {"assignee": R("tenant_user", "JO"), "level": "Organisational", "kpi": R("kpi", "K004"), "frequency": "Annually", "every": 1, "start_date": "2026-01-01", "status": "Active"},
            {"assignee": R("tenant_user", "PR"), "level": "Unit level", "unit": R("unit", "R103"), "kpi": R("kpi", "K009"), "frequency": "Hourly", "every": 4, "start_date": "2026-09-01", "status": "Active", "notes": "Every shift change."},
            {"assignee": R("tenant_user", "PR"), "level": "Unit level", "unit": R("unit", "R103"), "kpi": R("kpi", "K007"), "frequency": "Monthly", "every": 3, "start_date": "2026-04-01", "status": "Active"},
            {"assignee": R("tenant_user", "DK"), "level": "Unit level", "unit": R("unit", "R102"), "kpi": R("kpi", "K005"), "frequency": "Monthly", "every": 1, "start_date": "2026-02-01", "status": "Active"},
            {"assignee": R("tenant_user", "DK"), "level": "Unit level", "unit": R("unit", "R102"), "kpi": R("kpi", "K010"), "frequency": "Annually", "every": 1, "start_date": "2026-01-15", "status": "Paused"},
            {"assignee": R("tenant_user", "SC"), "level": "Organisational", "kpi": R("kpi", "K006"), "frequency": "Annually", "every": 1, "start_date": "2026-03-01", "status": "Active"},
            {"assignee": R("tenant_user", "NK"), "level": "Organisational", "kpi": R("kpi", "K008"), "frequency": "Monthly", "every": 6, "start_date": "2026-01-01", "status": "Active"},
            {"assignee": R("tenant_user", "SP"), "level": "Unit level", "unit": R("unit", "R104"), "kpi": R("kpi", "K002"), "frequency": "Monthly", "every": 1, "start_date": "2026-05-01", "status": "Active"},
        ],
    },
    {
        "key": "kpi_result", "name": "KPI Result", "group": "tenant",
        "fields": [
            *columns(
                [lookup("kpi", "KPI", "kpi", "kpi_title", req=True), lookup("assignee", "Entered By", "tenant_user", "full_name", req=True), ff("scope", "Scope", "dropdown", True, options=["Organisational", "Unit level"])],
                [lookup("unit", "Unit", "unit", "unit_name"), ff("period_label", "Period", req=True, placeholder="e.g., Sep 2026"), ff("entry_date", "Entry Date", "date", True)],
                "kpi",
            ),
            *columns(
                [ff("result_value", "Result", req=True, placeholder="e.g., Pass, 98 %, Compliant"), ff("outcome", "Outcome", "dropdown", True, options=["Pass", "Fail", "Partial", "Not applicable"])],
                [ff("entry_status", "Entry Status", "dropdown", True, options=["Up to Date", "Pending", "Due Soon", "Overdue"]), ff("next_entry_date", "Next Entry Date", "date")],
                "result",
            ),
            ff("notes", "Notes", "textarea"),
            ff("evidence", "Evidence", "file_upload"),
        ],
        "rows": [
            {"kpi": R("kpi", "K001"), "assignee": R("tenant_user", "JO"), "scope": "Organisational", "period_label": "Sep 2026", "entry_date": "2026-09-30", "result_value": "Pass", "outcome": "Pass", "entry_status": "Up to Date", "next_entry_date": "2026-11-01", "notes": "All quarterly reviews signed off."},
            {"kpi": R("kpi", "K004"), "assignee": R("tenant_user", "JO"), "scope": "Organisational", "period_label": "2026", "entry_date": "2026-03-31", "result_value": "Compliant", "outcome": "Pass", "entry_status": "Overdue", "next_entry_date": "2026-10-31", "notes": "Policy review overdue — board meeting rescheduled."},
            {"kpi": R("kpi", "K003"), "assignee": R("tenant_user", "JO"), "scope": "Organisational", "period_label": "2026", "entry_date": "2026-02-10", "result_value": "98 %", "outcome": "Pass", "entry_status": "Up to Date", "next_entry_date": "2027-01-01"},
            {"kpi": R("kpi", "K009"), "assignee": R("tenant_user", "PR"), "scope": "Unit level", "unit": R("unit", "R103"), "period_label": "12 Oct 2026 08:00", "entry_date": "2026-10-12", "result_value": "92 %", "outcome": "Partial", "entry_status": "Due Soon", "next_entry_date": "2026-10-12", "notes": "Two critical items deferred to next shift."},
            {"kpi": R("kpi", "K007"), "assignee": R("tenant_user", "PR"), "scope": "Unit level", "unit": R("unit", "R103"), "period_label": "Q3 2026", "entry_date": "2026-09-30", "result_value": "87 %", "outcome": "Partial", "entry_status": "Pending", "next_entry_date": "2026-12-31"},
            {"kpi": R("kpi", "K005"), "assignee": R("tenant_user", "DK"), "scope": "Unit level", "unit": R("unit", "R102"), "period_label": "Sep 2026", "entry_date": "2026-10-02", "result_value": "Fail", "outcome": "Fail", "entry_status": "Overdue", "next_entry_date": "2026-11-01", "notes": "Two shared admin accounts found; ticket raised."},
            {"kpi": R("kpi", "K006"), "assignee": R("tenant_user", "SC"), "scope": "Organisational", "period_label": "2026", "entry_date": "2026-06-14", "result_value": "2026-06-12", "outcome": "Pass", "entry_status": "Up to Date", "next_entry_date": "2027-06-01"},
            {"kpi": R("kpi", "K008"), "assignee": R("tenant_user", "NK"), "scope": "Organisational", "period_label": "H1 2026", "entry_date": "2026-07-05", "result_value": "94 %", "outcome": "Pass", "entry_status": "Up to Date", "next_entry_date": "2027-01-05"},
            {"kpi": R("kpi", "K002"), "assignee": R("tenant_user", "SP"), "scope": "Unit level", "unit": R("unit", "R104"), "period_label": "Sep 2026", "entry_date": "2026-10-01", "result_value": "Pass", "outcome": "Pass", "entry_status": "Pending", "next_entry_date": "2026-11-01"},
            {"kpi": R("kpi", "K010"), "assignee": R("tenant_user", "DK"), "scope": "Unit level", "unit": R("unit", "R102"), "period_label": "2025", "entry_date": "2026-01-20", "result_value": "LA", "outcome": "Partial", "entry_status": "Due Soon", "next_entry_date": "2026-10-20"},
        ],
    },
    {
        "key": "audit_plan", "name": "Audit Plan", "group": "tenant",
        "fields": [
            marker("wizard", "New Audit", "step_new"),
            ff("audit_title", "Audit Title", req=True, placeholder="e.g. IACS Cybersecurity Audit — Deepwater Horizon"),
            ff("description", "Description", "textarea", placeholder="Provide additional context about this audit..."),
            *columns(
                [ff("soa_scope", "SOA Scope", "dropdown", True, options=["Organizational", "Unit level"]), lookup("unit_type", "Unit type", "unit_type", "unit_type_name", visibility_rules=[{"driver_field": "soa_scope", "operator": "equals", "value": "Unit level"}]), lookup("unit", "Unit", "unit", "unit_name", visibility_rules=[{"driver_field": "soa_scope", "operator": "equals", "value": "Unit level"}]), ff("audit_type", "Audit Type", "dropdown", True, options=["Internal Audit", "External Audit", "Shareholder Audit", "Regulator Audit", "Review Activity"])],
                [ff("frequency", "Frequency", "dropdown", True, options=["One-time", "Quarterly", "Annual", "Rolling"]), ff("start_date", "Start Date", "date", True), ff("end_date", "End Date", "date", True), lookup("lead_auditor", "Lead Auditor", "tenant_user", "full_name", req=True)],
                "new",
            ),
            marker("wizard", "Framework Scope", "step_framework"),
            lookup("framework", "Framework", "framework", "framework_code", req=True),
            lookup("framework_version", "Framework Version", "framework_version", "version_label"),
            marker("wizard", "Define Scope", "step_scope"),
            ff("controls_in_scope", "Controls in Scope", "number", min=0),
            ff("scope_notes", "Scope Notes", "textarea", placeholder="Domains, sub-domains and objectives covered…"),
            marker("wizard", "Review", "step_review"),
            ff("status", "Status", "dropdown", True, options=["Draft", "Upcoming", "In Progress", "Completed"], default_value="Draft"),
        ],
        "rows": [
            {"_k": "A1", "audit_title": "IACS Cybersecurity Audit — Deepwater Horizon", "description": "Internal review of remote access, segmentation and IR readiness.", "soa_scope": "Unit level", "unit_type": R("unit_type", "RIG"), "unit": R("unit", "R101"), "audit_type": "Internal Audit", "frequency": "One-time", "start_date": "2026-07-01", "end_date": "2026-07-15", "lead_auditor": R("tenant_user", "MR"), "framework": R("framework", "ISA62443"), "framework_version": R("framework_version", "ISA13"), "controls_in_scope": 4, "scope_notes": "MFA, network segmentation, account control, incident response.", "status": "In Progress"},
            {"_k": "A2", "audit_title": "ISO 27001 Mid-Year Surveillance", "description": "Draft plan for organisational control sampling ahead of surveillance.", "soa_scope": "Organizational", "audit_type": "External Audit", "frequency": "Annual", "start_date": "2026-09-01", "end_date": "2026-09-05", "lead_auditor": R("tenant_user", "SC"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "controls_in_scope": 3, "status": "Draft"},
            {"_k": "A3", "audit_title": "Q4 Privileged Access Review", "description": "Upcoming quarterly review of privileged access across fleet assets.", "soa_scope": "Organizational", "audit_type": "Review Activity", "frequency": "Quarterly", "start_date": "2026-10-01", "end_date": "2026-10-10", "lead_auditor": R("tenant_user", "DK"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "controls_in_scope": 1, "status": "Upcoming"},
            {"_k": "A4", "audit_title": "SEM Hazards Analysis Follow-up", "description": "Completed follow-up on facility hazards analysis actions.", "soa_scope": "Unit level", "unit_type": R("unit_type", "RIG"), "unit": R("unit", "R102"), "audit_type": "Internal Audit", "frequency": "One-time", "start_date": "2026-03-20", "end_date": "2026-03-28", "lead_auditor": R("tenant_user", "RC"), "framework": R("framework", "APIRP75"), "framework_version": R("framework_version", "API19"), "controls_in_scope": 1, "status": "Completed"},
            {"_k": "A5", "audit_title": "North Sea Fleet ISM Internal Audit", "description": "Annual ISM Code internal audit across North Sea units.", "soa_scope": "Unit level", "unit_type": R("unit_type", "FLEET"), "unit": R("unit", "F4"), "audit_type": "Internal Audit", "frequency": "Annual", "start_date": "2026-11-02", "end_date": "2026-11-13", "lead_auditor": R("tenant_user", "ED"), "framework": R("framework", "ISM"), "controls_in_scope": 6, "status": "Upcoming"},
            {"_k": "A6", "audit_title": "Regulator OT Cyber Inspection", "description": "Regulator inspection of OT security controls on the Mariner.", "soa_scope": "Unit level", "unit_type": R("unit_type", "RIG"), "unit": R("unit", "R102"), "audit_type": "Regulator Audit", "frequency": "One-time", "start_date": "2026-08-10", "end_date": "2026-08-12", "lead_auditor": R("tenant_user", "MR"), "framework": R("framework", "ISA62443"), "framework_version": R("framework_version", "ISA13"), "controls_in_scope": 5, "status": "Completed"},
            {"_k": "A7", "audit_title": "Shareholder HSE Assurance Review", "description": "Shareholder-requested review of HSE performance and KPIs.", "soa_scope": "Organizational", "audit_type": "Shareholder Audit", "frequency": "Annual", "start_date": "2026-10-05", "end_date": "2026-10-16", "lead_auditor": R("tenant_user", "JO"), "framework": R("framework", "ISO45001"), "framework_version": R("framework_version", "ISO45"), "controls_in_scope": 4, "status": "In Progress"},
            {"_k": "A8", "audit_title": "Backup & Recovery Rolling Review", "description": "Rolling review of backup success and restore tests.", "soa_scope": "Organizational", "audit_type": "Review Activity", "frequency": "Rolling", "start_date": "2026-01-01", "end_date": "2026-12-31", "lead_auditor": R("tenant_user", "DK"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "controls_in_scope": 1, "status": "In Progress"},
            {"_k": "A9", "audit_title": "Voyager Asset Inventory Audit", "description": "Inventory completeness check before the GCC regulator visit.", "soa_scope": "Unit level", "unit_type": R("unit_type", "RIG"), "unit": R("unit", "R104"), "audit_type": "Internal Audit", "frequency": "One-time", "start_date": "2026-12-01", "end_date": "2026-12-04", "lead_auditor": R("tenant_user", "SP"), "framework": R("framework", "NIST"), "framework_version": R("framework_version", "NIST24"), "controls_in_scope": 2, "status": "Draft"},
            {"_k": "A10", "audit_title": "Training Effectiveness Review 2026", "description": "Review of awareness training completion and phishing results.", "soa_scope": "Organizational", "audit_type": "Review Activity", "frequency": "Annual", "start_date": "2026-06-01", "end_date": "2026-06-10", "lead_auditor": R("tenant_user", "NK"), "framework": R("framework", "ISO27001"), "framework_version": R("framework_version", "ISO22"), "controls_in_scope": 1, "status": "Completed"},
        ],
    },
]

# Datasources that link to form submissions — created once the forms exist.
TENANT_AFTER_FORMS = [
    {
        "key": "soa_change", "name": "SOA Change", "noun": "Change", "search": "Search changes...",
        "fields": [
            ref("soa", "SOA", "form:soa", "soa_title", req=True), sel("change_type", "Change", ["Created", "Control added", "Control removed", "Applicability changed", "Version upgraded", "Published"], req=True),
            ref("framework", "Framework", "framework", "framework_code"), txt("summary", "Summary", True), txt("before_value", "Before"), txt("after_value", "After"),
            txt("changed_by", "Changed By"), date("changed_on", "Changed On", True),
        ],
        "rows": [
            {"soa": R("soa", "ORG-ISO"), "change_type": "Created", "framework": R("framework", "ISO27001"), "summary": "Organizational SOA created from ISO 27001:2022.", "changed_by": "Sarah Chen", "changed_on": "2025-11-02"},
            {"soa": R("soa", "ORG-ISO"), "change_type": "Applicability changed", "framework": R("framework", "ISO27001"), "summary": "A.7.1 physical perimeter marked not applicable.", "before_value": "Applicable", "after_value": "Not applicable — landlord-owned", "changed_by": "Sarah Chen", "changed_on": "2026-01-14"},
            {"soa": R("soa", "ORG-ISO"), "change_type": "Published", "framework": R("framework", "ISO27001"), "summary": "Rev 3 published after management review.", "before_value": "Rev 2", "after_value": "Rev 3", "changed_by": "Hamad Al-Thani", "changed_on": "2026-03-10"},
            {"soa": R("soa", "ORG-NIST"), "change_type": "Version upgraded", "framework": R("framework", "NIST"), "summary": "Upgraded from CSF 1.1 to CSF 2.0.", "before_value": "2018-04", "after_value": "2024-02", "changed_by": "Sarah Chen", "changed_on": "2026-02-20"},
            {"soa": R("soa", "FLT1-ISO"), "change_type": "Control removed", "framework": R("framework", "ISO27001"), "summary": "Corporate HR controls inherited from the organisational SOA.", "before_value": "93 controls", "after_value": "72 controls", "changed_by": "James Okafor", "changed_on": "2026-04-28"},
            {"soa": R("soa", "FLT1-ISO"), "change_type": "Published", "framework": R("framework", "ISO27001"), "summary": "Americas Fleet SOA Rev 1 published.", "after_value": "Rev 1", "changed_by": "James Okafor", "changed_on": "2026-05-02"},
            {"soa": R("soa", "RIG102-ISA"), "change_type": "Control added", "framework": R("framework", "ISA62443"), "summary": "SR 1.13 remote access added after the IACS audit.", "before_value": "50 controls", "after_value": "51 controls", "changed_by": "David Kim", "changed_on": "2026-06-25"},
            {"soa": R("soa", "RIG102-ISA"), "change_type": "Published", "framework": R("framework", "ISA62443"), "summary": "Mariner SOA Rev 2 published.", "before_value": "Rev 1", "after_value": "Rev 2", "changed_by": "David Kim", "changed_on": "2026-07-01"},
            {"soa": R("soa", "FLT3-ISO"), "change_type": "Created", "framework": R("framework", "ISO27001"), "summary": "Middle East Fleet SOA drafted.", "changed_by": "Rachel Chen", "changed_on": "2026-09-15"},
            {"soa": R("soa", "ORG-ISO13"), "change_type": "Version upgraded", "framework": R("framework", "ISO27001"), "summary": "Superseded by the 2022 revision.", "before_value": "2013-10", "after_value": "2022-10", "changed_by": "Sarah Chen", "changed_on": "2025-11-02"},
        ],
    },
    {
        "key": "audit_task", "name": "Audit Task", "noun": "Task", "search": "Search tasks...",
        "fields": [
            txt("task_title", "Task", True), ref("audit", "Audit", "form:audit_plan", "audit_title", req=True), ref("control", "Control", "control", "control_title", req=True),
            ref("assignee", "Assignee", "tenant_user", "full_name", req=True), date("due_date", "Due Date", True),
            sel("priority", "Priority", ["High", "Medium", "Low"]), sel("status", "Status", ["Open", "In Progress", "Submitted", "Approved", "Rework"], req=True),
            txt("notes", "Notes"),
        ],
        "rows": [
            {"_k": "T1", "task_title": "MFA for remote access", "audit": R("audit_plan", "A1"), "control": R("control", "C001"), "assignee": R("tenant_user", "MR"), "due_date": "2026-07-08", "priority": "High", "status": "In Progress", "notes": "MFA for remote access — sample 25 sessions."},
            {"_k": "T2", "task_title": "Zone firewall rule review", "audit": R("audit_plan", "A1"), "control": R("control", "C008"), "assignee": R("tenant_user", "MR"), "due_date": "2026-07-10", "priority": "High", "status": "Open", "notes": "Firewall rule base between zones."},
            {"_k": "T3", "task_title": "Privileged session logging", "audit": R("audit_plan", "A1"), "control": R("control", "C004"), "assignee": R("tenant_user", "SC"), "due_date": "2026-07-12", "priority": "Medium", "status": "Submitted"},
            {"_k": "T4", "task_title": "Incident response exercise", "audit": R("audit_plan", "A1"), "control": R("control", "C005"), "assignee": R("tenant_user", "DK"), "due_date": "2026-07-14", "priority": "Medium", "status": "Rework", "notes": "Tabletop exercise evidence missing."},
            {"_k": "T5", "task_title": "HSE awareness training", "audit": R("audit_plan", "A7"), "control": R("control", "C007"), "assignee": R("tenant_user", "JO"), "due_date": "2026-10-14", "priority": "Medium", "status": "In Progress"},
            {"_k": "T6", "task_title": "Backup restore testing", "audit": R("audit_plan", "A8"), "control": R("control", "C002"), "assignee": R("tenant_user", "DK"), "due_date": "2026-10-31", "priority": "Low", "status": "Open"},
            {"_k": "T7", "task_title": "Shift equipment inspections", "audit": R("audit_plan", "A4"), "control": R("control", "C009"), "assignee": R("tenant_user", "RC"), "due_date": "2026-03-27", "priority": "High", "status": "Approved"},
            {"_k": "T8", "task_title": "Zones & conduits enforcement", "audit": R("audit_plan", "A6"), "control": R("control", "C008"), "assignee": R("tenant_user", "MR"), "due_date": "2026-08-12", "priority": "High", "status": "Approved"},
            {"_k": "T9", "task_title": "Quarterly privileged access review", "audit": R("audit_plan", "A3"), "control": R("control", "C004"), "assignee": R("tenant_user", "DK"), "due_date": "2026-10-09", "priority": "Medium", "status": "Open"},
            {"_k": "T10", "task_title": "Training completion review", "audit": R("audit_plan", "A10"), "control": R("control", "C007"), "assignee": R("tenant_user", "NK"), "due_date": "2026-06-09", "priority": "Low", "status": "Approved"},
        ],
    },
]

# Forms that look up datasources created after the first forms.
FORMS_AFTER = [
    {
        "key": "audit_assessment", "name": "Audit Assessment", "group": "tenant",
        "fields": [
            lookup("audit_task", "Audit Task", "audit_task", "task_title", req=True),
            *columns(
                [ff("design_effectiveness", "Design Effectiveness", "dropdown", True, options=["Poor", "Fair", "Good", "Very good", "Excellent"]), ff("operational_effectiveness", "Operational Effectiveness", "dropdown", True, options=["Poor", "Fair", "Good", "Very good", "Excellent"])],
                [ff("result", "Overall Result", "dropdown", True, options=["Effective", "Partially effective", "Ineffective"]), ff("assessed_on", "Assessed On", "date", True)],
                "rating",
            ),
            ff("findings", "Findings", "textarea", placeholder="What was tested and what was found…"),
            ff("corrective_action", "Corrective Action", "textarea", placeholder="Required action, owner and due date…"),
            ff("evidence", "Evidence", "file_upload"),
        ],
        "rows": [
            {"audit_task": R("audit_task", "T1"), "design_effectiveness": "Good", "operational_effectiveness": "Fair", "result": "Partially effective", "assessed_on": "2026-07-07", "findings": "3 of 25 remote sessions bypassed MFA through a legacy VPN profile.", "corrective_action": "Retire the legacy VPN profile — David Kim, 31 Jul."},
            {"audit_task": R("audit_task", "T3"), "design_effectiveness": "Very good", "operational_effectiveness": "Good", "result": "Effective", "assessed_on": "2026-07-11", "findings": "Privileged session logs reviewed weekly with sign-off."},
            {"audit_task": R("audit_task", "T4"), "design_effectiveness": "Fair", "operational_effectiveness": "Poor", "result": "Ineffective", "assessed_on": "2026-07-13", "findings": "No tabletop exercise held in the last 12 months.", "corrective_action": "Run an IR tabletop on the Pioneer — Q3."},
            {"audit_task": R("audit_task", "T7"), "design_effectiveness": "Good", "operational_effectiveness": "Good", "result": "Effective", "assessed_on": "2026-03-26", "findings": "Shift inspections recorded consistently."},
            {"audit_task": R("audit_task", "T8"), "design_effectiveness": "Excellent", "operational_effectiveness": "Very good", "result": "Effective", "assessed_on": "2026-08-11", "findings": "Zones and conduits documented and enforced."},
            {"audit_task": R("audit_task", "T10"), "design_effectiveness": "Good", "operational_effectiveness": "Very good", "result": "Effective", "assessed_on": "2026-06-08", "findings": "94 % completion; phishing click rate down to 4 %."},
            {"audit_task": R("audit_task", "T5"), "design_effectiveness": "Good", "operational_effectiveness": "Fair", "result": "Partially effective", "assessed_on": "2026-10-09", "findings": "Contractor crews missing refresher training.", "corrective_action": "Add contractors to the LMS — Nadia Khan, Nov."},
            {"audit_task": R("audit_task", "T2"), "design_effectiveness": "Fair", "operational_effectiveness": "Fair", "result": "Partially effective", "assessed_on": "2026-07-09", "findings": "Any-any rule between IT and OT DMZ.", "corrective_action": "Remove the rule after change review."},
            {"audit_task": R("audit_task", "T6"), "design_effectiveness": "Very good", "operational_effectiveness": "Excellent", "result": "Effective", "assessed_on": "2026-09-30", "findings": "Restore tests passed for all critical systems."},
            {"audit_task": R("audit_task", "T9"), "design_effectiveness": "Good", "operational_effectiveness": "Good", "result": "Effective", "assessed_on": "2026-10-05", "findings": "Quarterly privileged review complete."},
        ],
    },
]
