"""
Trial License Signup API Routes

Proxies the self-serve trial signup flow to the license server:
  POST /trial/request-otp  — forward to license server; sends OTP email
  POST /trial/verify-otp   — forward to license server; activates returned key

Email sending, OTP generation, and trial record creation are all handled
by the license server. The rivet_server just activates the returned key.
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Dict, Any
import logging

from app.config.config import LICENSE_SERVER_URL
from app.services.license_validator import LicenseValidator

logger = logging.getLogger(__name__)

router = APIRouter(tags=["trial"])

_TRIAL_DAYS = 14


class OtpRequestBody(BaseModel):
    name: str
    email: str
    company: str


class OtpVerifyBody(BaseModel):
    email: str
    otp: str



@router.post("/trial/request-otp")
async def request_trial_otp(body: OtpRequestBody) -> Dict[str, Any]:
    """
    Proxy to license server — generates OTP and sends verification email.
    """
    name    = body.name.strip()
    email   = body.email.strip().lower()
    company = body.company.strip()

    if not name or not email or not company:
        raise HTTPException(status_code=422, detail="name, email, and company are required")

    import httpx
    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(
                f"{LICENSE_SERVER_URL}/api/trial/request-otp",
                json={"name": name, "email": email, "company": company},
            )
        data = resp.json()
        if not resp.is_success:
            raise HTTPException(status_code=resp.status_code, detail=data.get("detail", "Failed to send verification code."))
        return {"success": True, "message": data.get("message", "Verification code sent. Please check your email.")}
    except HTTPException:
        raise
    except Exception as exc:
        logger.error(f"request-otp proxy error: {exc}")
        raise HTTPException(status_code=503, detail="Could not reach license server. Please try again.")


@router.post("/trial/verify-otp")
async def verify_trial_otp(body: OtpVerifyBody) -> Dict[str, Any]:
    """
    Proxy to license server — verifies OTP, creates trial license record,
    sends welcome email. Activates the returned license key locally.
    """
    email = body.email.strip().lower()
    otp   = body.otp.strip()

    import httpx
    try:
        async with httpx.AsyncClient(timeout=15) as client:
            resp = await client.post(
                f"{LICENSE_SERVER_URL}/api/trial/verify-otp",
                json={"email": email, "otp": otp},
            )
        data = resp.json()
        if not resp.is_success:
            raise HTTPException(status_code=resp.status_code, detail=data.get("detail", "Verification failed."))
    except HTTPException:
        raise
    except Exception as exc:
        logger.error(f"verify-otp proxy error: {exc}")
        raise HTTPException(status_code=503, detail="Could not reach license server. Please try again.")

    license_key = data.get("license_key")
    expires_at  = data.get("expires_at", "")

    # ── Activate the license key locally ─────────────────────────────────
    try:
        LicenseValidator.set_license_key(license_key)
    except Exception as e:
        logger.error(f"Failed to activate trial license for {email}: {e}")
        raise HTTPException(status_code=500, detail=f"License activation failed: {e}")

    logger.info(f"Trial activated via license server for {email}: {license_key[:8]}***")

    return {
        "success":     True,
        "license_key": license_key,
        "activated":   True,
        "expires_at":  expires_at,
        "message":     f"Your {_TRIAL_DAYS}-day trial is now active.",
    }

