#!/usr/bin/env python3

import os
import glob
import vobject
import subprocess

def import_vcf_to_contacts(vcf_path):
    with open(vcf_path, 'r') as f:
        vcard_data = f.read()

    # Parse the vCard data
    vcard = vobject.readOne(vcard_data)

    # Extract contact information
    name = str(vcard.n.value) if hasattr(vcard, 'n') else ''
    if hasattr(vcard, 'fn'):
        name = str(vcard.fn.value)

    phone = ''
    if hasattr(vcard, 'tel'):
        phone = str(vcard.tel.value)

    email = ''
    if hasattr(vcard, 'email'):
        email = str(vcard.email.value)

    # Prepare the termux-contact-add command
    cmd = ['termux-contact-add']
    if name:
        cmd.extend(['-n', name])
    if phone:
        cmd.extend(['-p', phone])
    if email:
        cmd.extend(['-e', email])

    # Execute the command
    if len(cmd) > 1:  # Only if there's something to add
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode == 0:
            print(f"Added contact: {name}")
        else:
            print(f"Failed to add contact {name}: {result.stderr}")

def main():
    vcf_dir = os.path.expanduser('./shenzhen_69.vcf')
    vcf_files = glob.glob(os.path.join(vcf_dir, '*.vcf'))

    if not vcf_files:
        print("No .vcf files found in ~/storage/movie/")
        return

    for vcf_file in vcf_files:
        print(f"Processing {vcf_file}")
        try:
            import_vcf_to_contacts(vcf_file)
        except Exception as e:
            print(f"Error processing {vcf_file}: {e}")

if __name__ == '__main__':
    main()
