"""
Webhook notifications for Slack and Microsoft Teams (#12).

Sends alerts when: test generation completes, fine-tuning/training finishes, CI job fails.
Follows email_service.py pattern — silent no-op when not configured.

Configure via env vars:
    QA_SLACK_WEBHOOK_URL   — Slack incoming webhook URL
    QA_TEAMS_WEBHOOK_URL   — Teams connector webhook URL
"""
from __future__ import annotations

import json
import os
import threading
import urllib.request
import urllib.error

_SLACK_URL = os.environ.get("QA_SLACK_WEBHOOK_URL", "")
_TEAMS_URL = os.environ.get("QA_TEAMS_WEBHOOK_URL", "")


def is_configured() -> bool:
    return bool(_SLACK_URL or _TEAMS_URL)


def _send_slack(text: str) -> bool:
    if not _SLACK_URL:
        return False
    payload = json.dumps({"text": text}).encode()
    try:
        req = urllib.request.Request(
            _SLACK_URL, data=payload,
            headers={"Content-Type": "application/json"}, method="POST",
        )
        with urllib.request.urlopen(req, timeout=10) as resp:
            return resp.status in (200, 201, 202)
    except Exception as e:
        print(f"  ⚠  Slack notification failed: {e}")
        return False


def _send_teams(text: str) -> bool:
    if not _TEAMS_URL:
        return False
    payload = json.dumps({
        "@type": "MessageCard",
        "@context": "http://schema.org/extensions",
        "summary": "QA Copilot Notification",
        "text": text,
    }).encode()
    try:
        req = urllib.request.Request(
            _TEAMS_URL, data=payload,
            headers={"Content-Type": "application/json"}, method="POST",
        )
        with urllib.request.urlopen(req, timeout=10) as resp:
            return resp.status in (200, 201, 202)
    except Exception as e:
        print(f"  ⚠  Teams notification failed: {e}")
        return False


def _send(text: str) -> None:
    def _do():
        if _SLACK_URL:
            _send_slack(text)
        if _TEAMS_URL:
            _send_teams(text)
    threading.Thread(target=_do, daemon=True).start()


def notify_generation_complete(story_key: str, test_count: int, username: str = "") -> None:
    if not is_configured():
        return
    who = f" by {username}" if username else ""
    _send(f"✅ *Generation complete*: {test_count} test(s) generated for `{story_key}`{who}")


def notify_training_complete(project: str, model: str) -> None:
    if not is_configured():
        return
    _send(f"🎓 *Training complete*: project `{project}` — model `{model}` is ready")


def notify_ci_failure(job_name: str, details: str = "") -> None:
    if not is_configured():
        return
    extra = f"\n> {details}" if details else ""
    _send(f"❌ *CI failure*: `{job_name}`{extra}")
