"""Chain Templates — pre-built action chain configurations.

Each template defines a reusable sequence of steps (email, webhook, wait, log)
that can be applied to any form. Templates are categorized by use case:
onboarding, notifications, nurture.

Template structure:
    {
        "id": "quote_approval",
        "name": "Quote Approval Workflow",
        "description": "Send quote, wait for approval, notify on response",
        "category": "onboarding",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "email",
                    "config": { "recipients": ["{{email}}"], "subject": "...", "body": "..." },
                    "on_success": "step_2"
                }
            ]
        }
    }
"""

from typing import Optional

# ─── Template Definitions ──────────────────────────────────────────────────────

_CHAIN_TEMPLATES = {
    # ── Onboarding ────────────────────────────────────────────────────────────
    "client_onboarding": {
        "id": "client_onboarding",
        "name": "Client Onboarding",
        "description": "Send welcome email, notify team, create follow-up task",
        "category": "onboarding",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "Welcome aboard, {{name}}!",
                        "body": "Hi {{name}},\n\nWelcome! We're excited to work with you.\n\nIf you have any questions, just hit reply.\n\nBest,\nThe Team",
                    },
                    "on_success": "step_2",
                },
                {
                    "id": "step_2",
                    "type": "http_request",
                    "config": {
                        "method": "POST",
                        "url": "{{webhook_url}}",
                        "headers": {"Content-Type": "application/json"},
                        "body": '{"event": "new_client", "name": "{{name}}", "email": "{{email}}"}',
                    },
                    "on_success": "step_3",
                },
                {"id": "step_3", "type": "log", "config": {"message": "Onboarding complete for {{name}} ({{email}})"}},
            ]
        },
    },
    "quote_approval": {
        "id": "quote_approval",
        "name": "Quote Approval Workflow",
        "description": "Send branded quote, wait for approval, notify team on response",
        "category": "onboarding",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "Your quote from {{company}}",
                        "body": "Hi {{name}},\n\nPlease review the attached quote.\n\nReply to this email to approve or request changes.\n\nBest regards,\n{{company}}",
                    },
                    "on_success": "step_2",
                },
                {"id": "step_2", "type": "wait", "config": {"duration_seconds": 86400}, "on_success": "step_3"},
                {
                    "id": "step_3",
                    "type": "email",
                    "config": {
                        "recipients": ["{{admin_email}}"],
                        "subject": "Quote follow-up needed: {{name}}",
                        "body": "Reminder: {{name}} ({{email}}) hasn't responded to their quote yet.",
                    },
                },
            ]
        },
    },
    "signup_welcome": {
        "id": "signup_welcome",
        "name": "Signup Welcome Sequence",
        "description": "Welcome email + day-3 check-in + day-7 engagement nudge",
        "category": "onboarding",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "Welcome to {{company}}, {{name}}!",
                        "body": "Hi {{name}},\n\nThanks for signing up! Here's what to do next:\n\n1. Complete your profile\n2. Explore our features\n3. Reach out if you need help\n\nBest,\nThe {{company}} Team",
                    },
                    "on_success": "step_2",
                },
                {
                    "id": "step_2",
                    "type": "wait",
                    "config": {"duration_seconds": 259200},  # 3 days
                    "on_success": "step_3",
                },
                {
                    "id": "step_3",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "How's it going, {{name}}?",
                        "body": "Hi {{name}},\n\nQuick check-in — how's everything going? We'd love to hear your feedback.",
                    },
                    "on_success": "step_4",
                },
                {
                    "id": "step_4",
                    "type": "wait",
                    "config": {"duration_seconds": 604800},  # 7 days
                    "on_success": "step_5",
                },
                {"id": "step_5", "type": "log", "config": {"message": "Welcome sequence complete for {{email}}"}},
            ]
        },
    },
    # ── Notifications ─────────────────────────────────────────────────────────
    "team_notification": {
        "id": "team_notification",
        "name": "Team Notification",
        "description": "Instant webhook + email to team on new submission",
        "category": "notifications",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "http_request",
                    "config": {
                        "method": "POST",
                        "url": "{{webhook_url}}",
                        "headers": {"Content-Type": "application/json"},
                        "body": '{"event": "new_submission", "name": "{{name}}", "email": "{{email}}", "phone": "{{phone}}"}',
                    },
                    "on_success": "step_2",
                },
                {
                    "id": "step_2",
                    "type": "email",
                    "config": {
                        "recipients": ["{{team_email}}"],
                        "subject": "New submission from {{name}}",
                        "body": "New form submission:\n\nName: {{name}}\nEmail: {{email}}\nPhone: {{phone}}\n\nView details in your dashboard.",
                    },
                },
            ]
        },
    },
    "submission_alert": {
        "id": "submission_alert",
        "name": "Submission Alert",
        "description": "Email the submitter a confirmation, notify admins",
        "category": "notifications",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "We received your submission!",
                        "body": "Hi {{name}},\n\nWe've received your submission and will get back to you within 24 hours.\n\nReference: {{submission.id}}\n\nThank you,\n{{company}}",
                    },
                    "on_success": "step_2",
                },
                {
                    "id": "step_2",
                    "type": "http_request",
                    "config": {
                        "method": "POST",
                        "url": "{{webhook_url}}",
                        "headers": {"Content-Type": "application/json"},
                        "body": '{"event": "submission_received", "id": "{{submission.id}}", "email": "{{email}}"}',
                    },
                },
            ]
        },
    },
    # ── Nurture ───────────────────────────────────────────────────────────────
    "lead_nurture": {
        "id": "lead_nurture",
        "name": "Lead Nurture Sequence",
        "description": "Day-1 value content, day-3 case study, day-7 CTA",
        "category": "nurture",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "Thanks for your interest, {{name}}",
                        "body": "Hi {{name}},\n\nThanks for showing interest in {{company}}.\n\nHere's something we think you'll find valuable: [resource link]\n\nBest,\n{{company}}",
                    },
                    "on_success": "step_2",
                },
                {
                    "id": "step_2",
                    "type": "wait",
                    "config": {"duration_seconds": 259200},  # 3 days
                    "on_success": "step_3",
                },
                {
                    "id": "step_3",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "{{name}}, here's what our clients say",
                        "body": "Hi {{name}},\n\nHere's a quick story about how we helped a client like you [case study link].\n\nWant to chat? Just reply.\n\nBest,\n{{company}}",
                    },
                    "on_success": "step_4",
                },
                {
                    "id": "step_4",
                    "type": "wait",
                    "config": {"duration_seconds": 604800},  # 7 days
                    "on_success": "step_5",
                },
                {
                    "id": "step_5",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "{{name}}, ready to move forward?",
                        "body": "Hi {{name}},\n\nIf you're ready to take the next step, we're here.\n\nBook a quick call: [calendar link]\n\nBest,\n{{company}}",
                    },
                    "on_success": "step_6",
                },
                {"id": "step_6", "type": "log", "config": {"message": "Nurture sequence complete for {{email}}"}},
            ]
        },
    },
    "follow_up_reminder": {
        "id": "follow_up_reminder",
        "name": "Follow-Up Reminder",
        "description": "Automated follow-up reminders at configurable intervals",
        "category": "nurture",
        "config": {
            "steps": [
                {
                    "id": "step_1",
                    "type": "wait",
                    "config": {"duration_seconds": 43200},  # 12 hours
                    "on_success": "step_2",
                },
                {
                    "id": "step_2",
                    "type": "email",
                    "config": {
                        "recipients": ["{{email}}"],
                        "subject": "Following up, {{name}}",
                        "body": "Hi {{name}},\n\nJust following up on your recent inquiry. Do you have any questions?\n\nBest,\n{{company}}",
                    },
                    "on_success": "step_3",
                },
                {
                    "id": "step_3",
                    "type": "wait",
                    "config": {"duration_seconds": 172800},  # 2 days
                    "on_success": "step_4",
                },
                {
                    "id": "step_4",
                    "type": "email",
                    "config": {
                        "recipients": ["{{admin_email}}"],
                        "subject": "Stale lead: {{name}}",
                        "body": "{{name}} ({{email}}) hasn't responded after 2 follow-ups.\n\nConsider reaching out personally.",
                    },
                },
            ]
        },
    },
}


# Public: raw template dict (for programmatic access)
CHAIN_TEMPLATES = _CHAIN_TEMPLATES


# ─── Public API ─────────────────────────────────────────────────────────────────


def get_chain_templates() -> list:
    """Return list of all chain templates (summary info)."""
    return [
        {
            "id": t["id"],
            "name": t["name"],
            "description": t["description"],
            "category": t["category"],
            "step_count": len(t["config"]["steps"]),
        }
        for t in _CHAIN_TEMPLATES.values()
    ]


def get_chain_templates_with_config() -> list:
    """Return all templates with their full chain_config."""
    return [
        {
            "id": t["id"],
            "name": t["name"],
            "description": t["description"],
            "category": t["category"],
            "chain_config": t["config"],
        }
        for t in _CHAIN_TEMPLATES.values()
    ]


def get_chain_template(template_id: str) -> dict | None:
    """Get a single template by ID, including full config."""
    template = _CHAIN_TEMPLATES.get(template_id)
    if template is None:
        return None
    return {
        "id": template["id"],
        "name": template["name"],
        "description": template["description"],
        "category": template["category"],
        "config": template["config"],
    }
