"""
Create custom DocTypes for remaining customer data:
  - Payment Method (Stripe, Paysafe/Bambora, Bank PPA)
  - Payment Arrangement (accord de paiement)
  - VoIP Line (PBX + 911 + ATA provisioning)

Run inside erpnext-backend-1:
  /home/frappe/frappe-bench/env/bin/python /home/frappe/frappe-bench/create_custom_doctypes.py
"""
import frappe
import os, sys

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
os.chdir("/home/frappe/frappe-bench/sites")
frappe.init(site="erp.gigafibre.ca", sites_path=".")
frappe.connect()
frappe.local.flags.ignore_permissions = True
print("Connected:", frappe.local.site)


def create_doctype(name, module, fields, **kwargs):
    if frappe.db.exists("DocType", name):
        print(f"  DocType '{name}' already exists — skipping")
        return
    doc = frappe.get_doc({
        "doctype": "DocType",
        "name": name,
        "module": module,
        "custom": 1,
        "is_submittable": kwargs.get("is_submittable", 0),
        "autoname": kwargs.get("autoname", "autoincrement"),
        "naming_rule": kwargs.get("naming_rule", "Autoincrement"),
        "fields": fields,
        "permissions": [
            {"role": "System Manager", "read": 1, "write": 1, "create": 1, "delete": 1},
            {"role": "Accounts User", "read": 1, "write": 1, "create": 1},
        ],
        **{k: v for k, v in kwargs.items() if k not in ("is_submittable", "autoname", "naming_rule")},
    })
    doc.insert(ignore_if_duplicate=True)
    frappe.db.commit()
    print(f"  Created DocType '{name}'")


# ═══════════════════════════════════════════════════════════
# 1. Payment Method
# ═══════════════════════════════════════════════════════════
print("\n=== Creating Payment Method ===")
create_doctype("Payment Method", "Custom", [
    {"fieldname": "customer", "fieldtype": "Link", "label": "Client", "options": "Customer",
     "reqd": 1, "in_list_view": 1, "in_standard_filter": 1},
    {"fieldname": "customer_name", "fieldtype": "Data", "label": "Nom client",
     "fetch_from": "customer.customer_name", "read_only": 1},
    {"fieldname": "cb1", "fieldtype": "Column Break"},
    {"fieldname": "provider", "fieldtype": "Select", "label": "Fournisseur",
     "options": "\nStripe\nPaysafe\nBank Draft", "reqd": 1, "in_list_view": 1, "in_standard_filter": 1},
    {"fieldname": "is_active", "fieldtype": "Check", "label": "Actif", "default": "1", "in_list_view": 1},
    {"fieldname": "is_auto_ppa", "fieldtype": "Check", "label": "PPA automatique"},
    {"fieldname": "sb_stripe", "fieldtype": "Section Break", "label": "Stripe",
     "depends_on": "eval:doc.provider=='Stripe'"},
    {"fieldname": "stripe_customer_id", "fieldtype": "Data", "label": "Stripe Customer ID"},
    {"fieldname": "stripe_ppa_enabled", "fieldtype": "Check", "label": "Stripe PPA actif"},
    {"fieldname": "cb_stripe", "fieldtype": "Column Break"},
    {"fieldname": "stripe_ppa_nocc", "fieldtype": "Check", "label": "Stripe PPA sans CC"},
    {"fieldname": "sb_paysafe", "fieldtype": "Section Break", "label": "Paysafe / Bambora",
     "depends_on": "eval:doc.provider=='Paysafe'"},
    {"fieldname": "paysafe_profile_id", "fieldtype": "Data", "label": "Profile ID"},
    {"fieldname": "paysafe_card_id", "fieldtype": "Data", "label": "Card ID"},
    {"fieldname": "cb_paysafe", "fieldtype": "Column Break"},
    {"fieldname": "paysafe_token", "fieldtype": "Data", "label": "Token"},
    {"fieldname": "paysafe_initial_txn", "fieldtype": "Data", "label": "Transaction initiale"},
    {"fieldname": "sb_bank", "fieldtype": "Section Break", "label": "PPA Bancaire",
     "depends_on": "eval:doc.provider=='Bank Draft'"},
    {"fieldname": "ppa_name", "fieldtype": "Data", "label": "Nom titulaire"},
    {"fieldname": "ppa_institution", "fieldtype": "Data", "label": "Code institution"},
    {"fieldname": "ppa_branch", "fieldtype": "Data", "label": "Code succursale"},
    {"fieldname": "cb_bank", "fieldtype": "Column Break"},
    {"fieldname": "ppa_account", "fieldtype": "Data", "label": "Numéro de compte"},
    {"fieldname": "ppa_amount", "fieldtype": "Currency", "label": "Montant PPA"},
    {"fieldname": "ppa_buffer", "fieldtype": "Currency", "label": "Buffer PPA"},
    {"fieldname": "sb_legacy", "fieldtype": "Section Break", "label": "Legacy", "collapsible": 1},
    {"fieldname": "legacy_account_id", "fieldtype": "Int", "label": "Legacy Account ID"},
],
    autoname="format:PM-{####}",
    naming_rule="Expression (Jinja)",
)


# ═══════════════════════════════════════════════════════════
# 2. Payment Arrangement
# ═══════════════════════════════════════════════════════════
print("\n=== Creating Payment Arrangement ===")
create_doctype("Payment Arrangement", "Custom", [
    {"fieldname": "customer", "fieldtype": "Link", "label": "Client", "options": "Customer",
     "reqd": 1, "in_list_view": 1, "in_standard_filter": 1},
    {"fieldname": "customer_name", "fieldtype": "Data", "label": "Nom client",
     "fetch_from": "customer.customer_name", "read_only": 1},
    {"fieldname": "status", "fieldtype": "Select", "label": "Statut",
     "options": "Pending\nOpen\nCompleted", "default": "Open", "in_list_view": 1, "in_standard_filter": 1},
    {"fieldname": "cb1", "fieldtype": "Column Break"},
    {"fieldname": "amount", "fieldtype": "Currency", "label": "Montant convenu",
     "reqd": 1, "in_list_view": 1},
    {"fieldname": "method", "fieldtype": "Select", "label": "Mode de paiement",
     "options": "\nPortail\nCheque\nTelephone\nPPA\nAutre"},
    {"fieldname": "sb_dates", "fieldtype": "Section Break", "label": "Dates"},
    {"fieldname": "date_agreed", "fieldtype": "Date", "label": "Date accord", "in_list_view": 1},
    {"fieldname": "date_due", "fieldtype": "Date", "label": "Date echeance", "in_list_view": 1},
    {"fieldname": "cb_dates", "fieldtype": "Column Break"},
    {"fieldname": "date_cutoff", "fieldtype": "Date", "label": "Date coupure"},
    {"fieldname": "sb_notes", "fieldtype": "Section Break", "label": "Notes"},
    {"fieldname": "staff", "fieldtype": "Data", "label": "Employe"},
    {"fieldname": "note", "fieldtype": "Small Text", "label": "Note"},
    {"fieldname": "reason", "fieldtype": "Small Text", "label": "Raison du changement"},
    {"fieldname": "sb_legacy", "fieldtype": "Section Break", "label": "Legacy", "collapsible": 1},
    {"fieldname": "legacy_accord_id", "fieldtype": "Int", "label": "Legacy Accord ID"},
    {"fieldname": "legacy_account_id", "fieldtype": "Int", "label": "Legacy Account ID"},
],
    autoname="format:PA-{####}",
    naming_rule="Expression (Jinja)",
)


# ═══════════════════════════════════════════════════════════
# 3. VoIP Line
# ═══════════════════════════════════════════════════════════
print("\n=== Creating VoIP Line ===")
create_doctype("VoIP Line", "Custom", [
    {"fieldname": "did", "fieldtype": "Data", "label": "DID (numero)", "reqd": 1,
     "unique": 1, "in_list_view": 1, "in_standard_filter": 1},
    {"fieldname": "customer", "fieldtype": "Link", "label": "Client", "options": "Customer",
     "reqd": 1, "in_list_view": 1, "in_standard_filter": 1},
    {"fieldname": "customer_name", "fieldtype": "Data", "label": "Nom client",
     "fetch_from": "customer.customer_name", "read_only": 1},
    {"fieldname": "cb1", "fieldtype": "Column Break"},
    {"fieldname": "service_location", "fieldtype": "Link", "label": "Lieu de service",
     "options": "Service Location", "in_standard_filter": 1},
    {"fieldname": "subscription", "fieldtype": "Link", "label": "Abonnement",
     "options": "Service Subscription"},
    {"fieldname": "status", "fieldtype": "Select", "label": "Statut",
     "options": "Active\nInactive\nSuspended", "default": "Active", "in_list_view": 1},

    {"fieldname": "sb_sip", "fieldtype": "Section Break", "label": "Configuration SIP"},
    {"fieldname": "caller_id", "fieldtype": "Data", "label": "Caller ID"},
    {"fieldname": "sip_password", "fieldtype": "Password", "label": "Mot de passe SIP"},
    {"fieldname": "extension", "fieldtype": "Data", "label": "Extension"},
    {"fieldname": "sip_context", "fieldtype": "Data", "label": "Contexte SIP"},
    {"fieldname": "cb_sip", "fieldtype": "Column Break"},
    {"fieldname": "max_calls", "fieldtype": "Int", "label": "Appels simultanes max", "default": "2"},
    {"fieldname": "call_timeout", "fieldtype": "Int", "label": "Timeout (sec)", "default": "30"},
    {"fieldname": "language", "fieldtype": "Select", "label": "Langue", "options": "fr\nen", "default": "fr"},
    {"fieldname": "country_whitelist", "fieldtype": "Small Text", "label": "Pays autorises"},

    {"fieldname": "sb_vm", "fieldtype": "Section Break", "label": "Messagerie vocale"},
    {"fieldname": "voicemail_enabled", "fieldtype": "Check", "label": "Messagerie activee"},
    {"fieldname": "vm_password", "fieldtype": "Data", "label": "Mot de passe messagerie"},
    {"fieldname": "vm_email", "fieldtype": "Data", "label": "Email notification messagerie"},
    {"fieldname": "cb_vm", "fieldtype": "Column Break"},
    {"fieldname": "vm_keep_msg", "fieldtype": "Check", "label": "Conserver messages"},
    {"fieldname": "vm_disk_quota", "fieldtype": "Int", "label": "Quota disque (Mo)", "default": "180"},

    {"fieldname": "sb_911", "fieldtype": "Section Break", "label": "Adresse 911"},
    {"fieldname": "e911_first_name", "fieldtype": "Data", "label": "Prenom 911"},
    {"fieldname": "e911_last_name", "fieldtype": "Data", "label": "Nom 911"},
    {"fieldname": "e911_street_number", "fieldtype": "Data", "label": "Numero civique"},
    {"fieldname": "e911_apt", "fieldtype": "Data", "label": "Appartement"},
    {"fieldname": "e911_street_name", "fieldtype": "Data", "label": "Rue"},
    {"fieldname": "cb_911", "fieldtype": "Column Break"},
    {"fieldname": "e911_city", "fieldtype": "Data", "label": "Ville"},
    {"fieldname": "e911_state", "fieldtype": "Data", "label": "Province"},
    {"fieldname": "e911_zip", "fieldtype": "Data", "label": "Code postal"},
    {"fieldname": "e911_cauca_code", "fieldtype": "Data", "label": "Code CAUCA"},
    {"fieldname": "e911_class", "fieldtype": "Select", "label": "Classe service",
     "options": "RES\nBUS\nCOM", "default": "RES"},
    {"fieldname": "e911_enhanced", "fieldtype": "Check", "label": "Enhanced 911", "default": "1"},
    {"fieldname": "e911_synced", "fieldtype": "Check", "label": "Synchronise avec fournisseur 911"},
    {"fieldname": "e911_info", "fieldtype": "Data", "label": "Info supplementaire 911"},

    {"fieldname": "sb_ata", "fieldtype": "Section Break", "label": "Equipement ATA"},
    {"fieldname": "ata_model", "fieldtype": "Data", "label": "Modele ATA"},
    {"fieldname": "ata_mac", "fieldtype": "Data", "label": "MAC ATA"},
    {"fieldname": "cb_ata", "fieldtype": "Column Break"},
    {"fieldname": "ata_password", "fieldtype": "Data", "label": "Mot de passe ATA"},
    {"fieldname": "international_enabled", "fieldtype": "Check", "label": "Appels internationaux"},

    {"fieldname": "sb_legacy", "fieldtype": "Section Break", "label": "Legacy", "collapsible": 1},
    {"fieldname": "legacy_pbx_id", "fieldtype": "Int", "label": "Legacy PBX ID"},
    {"fieldname": "legacy_account_id", "fieldtype": "Int", "label": "Legacy Account ID"},
    {"fieldname": "legacy_delivery_id", "fieldtype": "Int", "label": "Legacy Delivery ID"},
    {"fieldname": "legacy_service_id", "fieldtype": "Int", "label": "Legacy Service ID"},
],
    autoname="field:did",
    naming_rule="By fieldname",
)


# ═══════════════════════════════════════════════════════════
# 4. Add is_suspended to Customer if not exists
# ═══════════════════════════════════════════════════════════
print("\n=== Adding Customer custom fields ===")

for field_def in [
    {"dt": "Customer", "fieldname": "is_suspended", "fieldtype": "Check",
     "label": "Suspendu", "insert_after": "is_bad_payer"},
    {"dt": "Customer", "fieldname": "suspension_note", "fieldtype": "Data",
     "label": "Note suspension", "insert_after": "is_suspended",
     "depends_on": "eval:doc.is_suspended"},
]:
    if not frappe.db.exists("Custom Field", {"dt": field_def["dt"], "fieldname": field_def["fieldname"]}):
        cf = frappe.get_doc({"doctype": "Custom Field", **field_def})
        cf.insert(ignore_permissions=True)
        frappe.db.commit()
        print(f"  Added {field_def['dt']}.{field_def['fieldname']}")
    else:
        print(f"  {field_def['dt']}.{field_def['fieldname']} already exists")


frappe.destroy()
print("\nAll doctypes created!")
