"""People applet - Standalone contact management interface.

Provides interactive contact selection and cleanup using Google Contacts API.
Allows browsing autocomplete contacts and cleaning up invalid email addresses.

Key Features:
- Autocomplete contact selection from Google Contacts
- Invalid contact cleanup (F5)
- TODO: Contact deletion (Control+Delete)
- TODO: Email launching

See google_contacts.py for underlying utility functions and dialog classes.
"""

from ..google_contacts import ContactsInputDialog, get_other_contacts
from ..subdialogs import Applet
from ..key_handler import KeyHandler
from typing import Any


class PeopleDialog(Applet, ContactsInputDialog):  # type: ignore[misc]
    """Standalone applet for managing contacts from Google People API.

    Combines Applet and ContactsInputDialog to provide contact management UI.
    Supports autocomplete contact selection and cleanup of invalid contacts.

    Hotkeys:
        F5: Clean up invalid contacts from Google Contacts.
        Control+Delete: Delete selected contact (TODO: implement).

    Methods:
        ok(): Returns selected contact (TODO: implement email launch).
        command_cleanup(): Fetch all contacts, prompt to delete invalid ones.
        command_delete_contact(): Delete selected contact (TODO: implement).
        delete_contact(): Delete contact by resource name (TODO: implement).

    Todo:
        - Implement email launch from ok()
        - Save resourceName metadata on contacts for deletion
        - Implement actual delete_contact() via Google API
        - Update cache and recents after deletion
    """

    def ok(self, modified_name: str) -> None:  # type: ignore[override]
        """Return selected contact. TODO: Launch email to contact."""
        contact = self.get_result()  # type: ignore[func-returns-value]
        if contact:
            self.say_strings(f'implement launch email to {contact}')

    @KeyHandler.hotkey("F5")
    def command_cleanup(self, modified_name: str) -> None:
        """Clean up invalid contacts from Google People API.

        Fetches all contacts, identifies invalid email addresses, prompts user
        to delete/ignore each one. Reports count of deleted contacts at end.

        Todo:
            Implement save to cache after deletions, update recents cache.
        """
        assert self.app is not None
        self.errors: list[tuple[Any, str, str]] = []
        get_other_contacts(self.app.google_creds, errors=self.errors)
        total = len(self.errors)
        count = 0
        self.purge_speech = False
        for contact, error_message, contact_string in self.errors:
            # print(error_message)
            explanation = f"{contact_string}, {error_message}"
            user_result = self.message(
                title=explanation, buttons=['Delete', 'Ignore', 'Cancel Cleanup']
            )
            if user_result == 'Delete':
                if self.delete_contact(contact['resourceName']):
                    count += 1
            elif user_result == 'Ignore':
                continue
            else:
                self.say_strings('Cancelled cleanup')
                break
        self.say_strings(
            f"deleted {count} contacts, {total-count} errors remaining. Now implement save to cache, delete from recents  and also implement selective delete from recents cache in command_delete_contact.",
            interrupt=False,
        )
        self.purge_speech = True

    @KeyHandler.hotkey("Control+Delete")
    def command_delete_contact(self, modified_name: str) -> None:
        """Delete selected contact. TODO: Save resourceName metadata first."""
        self.say_strings(
            'Implement saving of resourceName on each contact so can pass as argument to self.delete_contact'
        )

    def delete_contact(self, resource_name: str) -> bool:
        """Delete contact by resource name via Google API.

        Args:
            resource_name: Google People API resource name (e.g., people/c123456).

        Returns:
            True if deletion successful (currently always True - TODO: implement).

        Todo:
            Implement execute_with_retry() delete_command using resource_name.
        """
        self.say_strings('execute_with_retry  delete_command using the resource_name argument')
        return True
