"""XAdES authentication with an MCU-issued certificate (DEMO / PRODUCTION).

On the DEMO and PRODUCTION environments KSeF requires a certificate obtained
from MCU (https://ap-demo.ksef.mf.gov.pl/web/ for DEMO).  Self-signed
certificates generated by the SDK are accepted on the TEST environment only.

Prerequisites
-------------
1. Log into MCU with your Profil Zaufany or electronic seal.
2. Generate a **signing** certificate (not just a login certificate).
3. Download the two files provided by KSEF:
   - certificate: ``<NIP>.pem``  (the ``.pem`` file)
   - private key: ``<NIP>.key``  (the ``.key`` file)

Usage
-----
Set the environment variables before running::

    KSEF_NIP=1234567890 KSEF_CERT=1234567890.pem KSEF_KEY=1234567890.key python auth_xades_demo.py

Or edit the constants below directly.
"""

from __future__ import annotations

import os

from ksef2 import Client, Environment
from ksef2.core.xades import load_certificate_from_pem, load_private_key_from_pem

NIP = os.environ.get("KSEF_NIP", "1234567890")
CERT_PATH = os.environ.get("KSEF_CERT", f"{NIP}.pem")  # certificate — .pem from KSEF
KEY_PATH = os.environ.get("KSEF_KEY", f"{NIP}.key")  # private key  — .key from KSEF
# KEY_PASSWORD = b"secret"  # uncomment if the key file is encrypted


def main() -> None:
    # Load the certificate and private key obtained from MCU
    cert = load_certificate_from_pem(CERT_PATH)
    key = load_private_key_from_pem(
        KEY_PATH,
        # password=KEY_PASSWORD,
    )

    client = Client(Environment.DEMO)  # or Environment.PRODUCTION

    print("Authenticating via XAdES (MCU certificate) ...")
    auth = client.auth.authenticate_xades(
        nip=NIP,
        cert=cert,
        private_key=key,
        verify_chain=False,  # set True only if your cert has a verifiable chain
    )

    print(f"Access token:  {auth.access_token[:40]}…")
    print(f"  Valid until: {auth.auth_tokens.access_token.valid_until}")
    print(f"Refresh token: {auth.refresh_token[:40]}…")
    print(f"  Valid until: {auth.auth_tokens.refresh_token.valid_until}")


if __name__ == "__main__":
    main()
