"""
Email Autoconfiguration Views

Provides automatic email client configuration for:
- Mozilla Autoconfig (Thunderbird, etc.)
- Microsoft Autodiscover (Outlook)
- Apple Mail configuration profile

These endpoints allow email clients to automatically configure
IMAP and SMTP settings for smoothschedule.com email addresses.
"""

from django.http import HttpResponse
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt


class MozillaAutoconfigView(View):
    """
    Mozilla Autoconfig endpoint.

    URL: /mail/config-v1.1.xml or /.well-known/autoconfig/mail/config-v1.1.xml

    Used by:
    - Mozilla Thunderbird
    - Evolution
    - Other clients supporting Mozilla autoconfig
    """

    def get(self, request):
        # Get email address from query parameter
        email = request.GET.get('emailaddress', '')

        # Extract local part if email provided
        if '@' in email:
            local_part = email.split('@')[0]
        else:
            local_part = '%EMAILLOCALPART%'

        xml_content = f'''<?xml version="1.0" encoding="UTF-8"?>
<clientConfig version="1.1">
  <emailProvider id="smoothschedule.com">
    <domain>smoothschedule.com</domain>
    <displayName>SmoothSchedule Mail</displayName>
    <displayShortName>SmoothSchedule</displayShortName>

    <incomingServer type="imap">
      <hostname>mail.talova.net</hostname>
      <port>993</port>
      <socketType>SSL</socketType>
      <authentication>password-cleartext</authentication>
      <username>%EMAILADDRESS%</username>
    </incomingServer>

    <outgoingServer type="smtp">
      <hostname>mail.talova.net</hostname>
      <port>587</port>
      <socketType>STARTTLS</socketType>
      <authentication>password-cleartext</authentication>
      <username>%EMAILADDRESS%</username>
    </outgoingServer>

    <documentation url="https://smoothschedule.com/help/email">
      <descr lang="en">Email configuration help</descr>
    </documentation>
  </emailProvider>
</clientConfig>'''

        return HttpResponse(
            xml_content,
            content_type='application/xml; charset=utf-8'
        )


@method_decorator(csrf_exempt, name='dispatch')
class MicrosoftAutodiscoverView(View):
    """
    Microsoft Autodiscover endpoint.

    URL: /autodiscover/autodiscover.xml

    Used by:
    - Microsoft Outlook
    - Windows Mail
    - Other Microsoft clients
    """

    def post(self, request):
        # Microsoft Autodiscover uses POST with XML body
        # Extract email from request body if needed

        xml_content = '''<?xml version="1.0" encoding="UTF-8"?>
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">
  <Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a">
    <Account>
      <AccountType>email</AccountType>
      <Action>settings</Action>
      <Protocol>
        <Type>IMAP</Type>
        <Server>mail.talova.net</Server>
        <Port>993</Port>
        <SSL>on</SSL>
        <AuthRequired>on</AuthRequired>
        <LoginName></LoginName>
      </Protocol>
      <Protocol>
        <Type>SMTP</Type>
        <Server>mail.talova.net</Server>
        <Port>587</Port>
        <SSL>on</SSL>
        <Encryption>TLS</Encryption>
        <AuthRequired>on</AuthRequired>
        <LoginName></LoginName>
      </Protocol>
    </Account>
  </Response>
</Autodiscover>'''

        return HttpResponse(
            xml_content,
            content_type='application/xml; charset=utf-8'
        )

    def get(self, request):
        # Some clients may use GET
        return self.post(request)


class AppleConfigProfileView(View):
    """
    Apple Configuration Profile for iOS/macOS Mail.

    URL: /email/apple-profile.mobileconfig

    Provides a downloadable .mobileconfig file that can be
    installed on iOS/macOS devices for automatic email setup.
    """

    def get(self, request):
        email = request.GET.get('email', '')

        if not email or '@' not in email:
            return HttpResponse(
                'Email parameter required (e.g., ?email=user@smoothschedule.com)',
                status=400
            )

        # Generate a unique identifier for this profile
        import uuid
        profile_uuid = str(uuid.uuid4()).upper()
        account_uuid = str(uuid.uuid4()).upper()

        local_part = email.split('@')[0]
        display_name = local_part.replace('.', ' ').replace('-', ' ').title()

        plist_content = f'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>PayloadContent</key>
    <array>
        <dict>
            <key>EmailAccountDescription</key>
            <string>SmoothSchedule Mail</string>
            <key>EmailAccountName</key>
            <string>{display_name}</string>
            <key>EmailAccountType</key>
            <string>EmailTypeIMAP</string>
            <key>EmailAddress</key>
            <string>{email}</string>
            <key>IncomingMailServerAuthentication</key>
            <string>EmailAuthPassword</string>
            <key>IncomingMailServerHostName</key>
            <string>mail.talova.net</string>
            <key>IncomingMailServerPortNumber</key>
            <integer>993</integer>
            <key>IncomingMailServerUseSSL</key>
            <true/>
            <key>IncomingMailServerUsername</key>
            <string>{email}</string>
            <key>OutgoingMailServerAuthentication</key>
            <string>EmailAuthPassword</string>
            <key>OutgoingMailServerHostName</key>
            <string>mail.talova.net</string>
            <key>OutgoingMailServerPortNumber</key>
            <integer>587</integer>
            <key>OutgoingMailServerUseSSL</key>
            <true/>
            <key>OutgoingMailServerUsername</key>
            <string>{email}</string>
            <key>OutgoingPasswordSameAsIncomingPassword</key>
            <true/>
            <key>PayloadDescription</key>
            <string>Configures email account for {email}</string>
            <key>PayloadDisplayName</key>
            <string>SmoothSchedule Email</string>
            <key>PayloadIdentifier</key>
            <string>com.smoothschedule.email.account.{account_uuid}</string>
            <key>PayloadType</key>
            <string>com.apple.mail.managed</string>
            <key>PayloadUUID</key>
            <string>{account_uuid}</string>
            <key>PayloadVersion</key>
            <integer>1</integer>
            <key>SMIMEEnablePerMessageSwitch</key>
            <false/>
        </dict>
    </array>
    <key>PayloadDescription</key>
    <string>Email configuration for SmoothSchedule</string>
    <key>PayloadDisplayName</key>
    <string>SmoothSchedule Email Configuration</string>
    <key>PayloadIdentifier</key>
    <string>com.smoothschedule.email.profile.{profile_uuid}</string>
    <key>PayloadOrganization</key>
    <string>SmoothSchedule</string>
    <key>PayloadRemovalDisallowed</key>
    <false/>
    <key>PayloadType</key>
    <string>Configuration</string>
    <key>PayloadUUID</key>
    <string>{profile_uuid}</string>
    <key>PayloadVersion</key>
    <integer>1</integer>
</dict>
</plist>'''

        response = HttpResponse(
            plist_content,
            content_type='application/x-apple-aspen-config'
        )
        response['Content-Disposition'] = f'attachment; filename="smoothschedule-email.mobileconfig"'
        return response


class WellKnownAutoconfigView(View):
    """
    .well-known autoconfig redirect.

    Some clients look for /.well-known/autoconfig/mail/config-v1.1.xml
    """

    def get(self, request):
        from django.shortcuts import redirect
        email = request.GET.get('emailaddress', '')
        url = '/mail/config-v1.1.xml'
        if email:
            url += f'?emailaddress={email}'
        return redirect(url)
