#!/usr/bin/env python3
"""
eSIM Profile Personalizer for Veloso Telecom FWA
Uses pySim SAIP personalization API to customize template .der profiles.

Usage:
    python3 personalize_profile.py \
        --template /path/to/template.der \
        --iccid 89550199999999999 \
        --imsi 724990000000001 \
        --ki 00112233445566778899AABBCCDDEEFF \
        --opc FFEEDDCCBBAA99887766554433221100 \
        --matching-id MY-ESIM-001 \
        --output /path/to/smdpp-data/upp/
"""

import sys
import os
import argparse
import json

# Add pySim to path
PYSIM_DIR = os.environ.get('PYSIM_DIR', '/home/produto01/.gemini/antigravity/scratch/pysim')
sys.path.insert(0, PYSIM_DIR)

from pySim.esim.saip import ProfileElementSequence
from pySim.esim.saip.personalization import Iccid, Imsi, K, Opc


def personalize_profile(template_path: str, iccid: str, imsi: str, ki: str, opc: str,
                         matching_id: str, output_dir: str) -> dict:
    """
    Personalize a template .der profile with the given subscriber data.

    Returns a dict with status and details.
    """
    result = {
        'success': False,
        'matching_id': matching_id,
        'output_path': '',
        'error': ''
    }

    # Validate inputs
    if not os.path.isfile(template_path):
        result['error'] = f'Template file not found: {template_path}'
        return result

    if not os.path.isdir(output_dir):
        result['error'] = f'Output directory not found: {output_dir}'
        return result

    output_path = os.path.join(output_dir, f'{matching_id}.der')

    try:
        # Read template
        with open(template_path, 'rb') as f:
            template_data = f.read()

        # Parse the template profile
        pes = ProfileElementSequence.from_der(template_data)

        # Apply ICCID
        iccid_param = Iccid(iccid)
        iccid_param.apply(pes)

        # Apply IMSI
        imsi_param = Imsi(imsi)
        imsi_param.apply(pes)

        # Apply KI (authentication key)
        ki_param = K(ki)
        ki_param.apply(pes)

        # Apply OPc
        opc_param = Opc(opc)
        opc_param.apply(pes)

        # Serialize back to DER
        personalized_data = pes.to_der()

        # Write output
        with open(output_path, 'wb') as f:
            f.write(personalized_data)

        result['success'] = True
        result['output_path'] = output_path
        result['size'] = len(personalized_data)

    except Exception as e:
        result['error'] = str(e)

    return result


def main():
    parser = argparse.ArgumentParser(description='Personalize eSIM profile from template')
    parser.add_argument('--template', required=True, help='Path to template .der file')
    parser.add_argument('--iccid', required=True, help='ICCID (19-20 digits)')
    parser.add_argument('--imsi', required=True, help='IMSI (15 digits)')
    parser.add_argument('--ki', required=True, help='KI / Authentication Key (32 hex chars)')
    parser.add_argument('--opc', required=True, help='OPc (32 hex chars)')
    parser.add_argument('--matching-id', required=True, help='Matching ID (filename without .der)')
    parser.add_argument('--output', required=True, help='Output directory for .der file')
    args = parser.parse_args()

    result = personalize_profile(
        template_path=args.template,
        iccid=args.iccid,
        imsi=args.imsi,
        ki=args.ki,
        opc=args.opc,
        matching_id=args.matching_id,
        output_dir=args.output
    )

    # Output as JSON for Node.js to parse
    print(json.dumps(result))
    sys.exit(0 if result['success'] else 1)


if __name__ == '__main__':
    main()
