from datetime import datetime, timezone
import argparse
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from app import create_app
from app.services.email_service import EmailService
from app.services.settings_service import SettingsService


def main() -> int:
    parser = argparse.ArgumentParser(description="Send a real SMTP test email using the current application settings.")
    parser.add_argument("--to", dest="recipient", help="Recipient email address. Defaults to MAIL_FROM_ADDRESS.")
    parser.add_argument("--subject", default="KHF SMP SMTP Test", help="Custom email subject.")
    args = parser.parse_args()

    app = create_app("development")
    with app.app_context():
        config = SettingsService.mail_config()
        recipient = args.recipient or config["from_address"]
        if not recipient:
            print("No recipient address was provided and MAIL_FROM_ADDRESS is empty.")
            return 1

        body = "\n".join(
            [
                "This is a live SMTP test from KHF SMP.",
                f"Timestamp: {datetime.now(timezone.utc).isoformat()}",
                f"SMTP host: {config['host'] or '(not configured)'}",
                f"TLS enabled: {config['use_tls']}",
                "",
                "If you received this message, live email delivery is working.",
            ]
        )
        sent = EmailService.send_email([recipient], args.subject, body)
        if sent:
            print(f"Email sent successfully to {recipient}.")
            return 0

        print("Email was not sent. Check SMTP configuration and application logs.")
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
