"""
Automatic SLA policy generation at client setup.

When a new client is created we seed a standard 4-tier SLA policy set
(critical / high / medium / low) so the client is never left with zero SLAs.

Two sources:
  * AI (Claude) — when ANTHROPIC_API_KEY is configured, we ask Claude to tune
    the response/resolution/escalation targets to the client's tier + industry.
  * Defaults — a deterministic tier-based matrix used when there is no API key
    or the AI call fails. This means the feature always works, with or without AI.

Idempotent: does nothing if the client already has SLA policies.
"""
import json

from django.conf import settings

from .models import SLAPolicy


# Tier-based default targets, in MINUTES: (first_response, resolution, escalation).
# Higher tiers get faster commitments. Order of priorities: critical/high/medium/low.
TIER_DEFAULTS = {
    'platinum': {
        'critical': (15, 240, 30),
        'high':     (30, 480, 60),
        'medium':   (60, 1440, 120),
        'low':      (120, 2880, 240),
    },
    'gold': {
        'critical': (30, 360, 60),
        'high':     (60, 720, 120),
        'medium':   (120, 1440, 240),
        'low':      (240, 2880, 480),
    },
    'silver': {
        'critical': (60, 480, 120),
        'high':     (120, 1440, 240),
        'medium':   (240, 2880, 480),
        'low':      (480, 4320, 960),
    },
    'bronze': {
        'critical': (120, 720, 240),
        'high':     (240, 1440, 480),
        'medium':   (480, 2880, 960),
        'low':      (960, 5760, 1440),
    },
}

PRIORITY_LABEL = {
    'critical': 'Critical Response',
    'high': 'High Priority Response',
    'medium': 'Standard Response',
    'low': 'Low Priority Response',
}


def _default_policy_specs(client):
    """Return a list of policy dicts from the tier-based matrix."""
    tier = (client.tier or 'bronze').lower()
    matrix = TIER_DEFAULTS.get(tier, TIER_DEFAULTS['bronze'])
    specs = []
    for priority in ('critical', 'high', 'medium', 'low'):
        fr, res, esc = matrix[priority]
        specs.append({
            'name': PRIORITY_LABEL[priority],
            'priority': priority,
            'category': 'general',
            'first_response_minutes': fr,
            'resolution_minutes': res,
            'escalation_minutes': esc,
        })
    return specs


def _ai_policy_specs(client):
    """Ask Claude to propose the 4-tier SLA set. Returns specs list or None on failure.

    Checks for a key BEFORE importing anthropic so a server without the package
    installed simply falls through to the tier defaults instead of raising.
    """
    api_key = getattr(settings, 'ANTHROPIC_API_KEY', '')
    if not api_key:
        return None
    try:
        import anthropic
    except ImportError:
        return None

    prompt = f"""You are an SLA policy designer for a call-center CRM.
Design a Service Level Agreement policy set for this client:

Client name: {client.name}
Industry: {client.industry or 'general'}
Service tier: {client.tier or 'bronze'} (platinum=fastest/premium, bronze=basic)

Produce exactly 4 policies, one per priority: critical, high, medium, low.
Higher tiers must have faster (smaller) times. All times are in MINUTES.

Respond ONLY with valid JSON (no markdown, no commentary):
{{
  "policies": [
    {{"priority": "critical", "first_response_minutes": 0, "resolution_minutes": 0, "escalation_minutes": 0}},
    {{"priority": "high", "first_response_minutes": 0, "resolution_minutes": 0, "escalation_minutes": 0}},
    {{"priority": "medium", "first_response_minutes": 0, "resolution_minutes": 0, "escalation_minutes": 0}},
    {{"priority": "low", "first_response_minutes": 0, "resolution_minutes": 0, "escalation_minutes": 0}}
  ]
}}

Rules:
- first_response_minutes < resolution_minutes for every policy.
- critical fastest, low slowest.
- Keep values realistic (critical first response 15-120 min; low resolution up to a few days)."""

    try:
        cli = anthropic.Anthropic(api_key=api_key)
        msg = cli.messages.create(
            model='claude-haiku-4-5-20251001',
            max_tokens=512,
            messages=[{'role': 'user', 'content': prompt}],
        )
        data = json.loads(msg.content[0].text.strip())
        specs = []
        for p in data['policies']:
            priority = p['priority']
            if priority not in PRIORITY_LABEL:
                return None
            specs.append({
                'name': PRIORITY_LABEL[priority],
                'priority': priority,
                'category': 'general',
                'first_response_minutes': int(p['first_response_minutes']),
                'resolution_minutes': int(p['resolution_minutes']),
                'escalation_minutes': int(p['escalation_minutes']),
            })
        # sanity: need all 4 priorities
        if {s['priority'] for s in specs} != {'critical', 'high', 'medium', 'low'}:
            return None
        return specs
    except Exception:
        return None


def create_sla_policies_for_client(client, use_ai=True):
    """Create a standard SLA policy set for a client.

    Returns dict: {'created': int, 'source': 'ai'|'default'|'skipped'}.
    Idempotent — skips clients that already have SLA policies.
    """
    if client.sla_policies.exists():
        return {'created': 0, 'source': 'skipped'}

    specs = None
    source = 'default'
    if use_ai:
        # Never let an AI failure stop the tier defaults from being created.
        try:
            specs = _ai_policy_specs(client)
        except Exception:
            specs = None
        if specs:
            source = 'ai'
    if not specs:
        specs = _default_policy_specs(client)

    policies = [SLAPolicy(client=client, is_active=True, **spec) for spec in specs]
    SLAPolicy.objects.bulk_create(policies)
    return {'created': len(policies), 'source': source}
