"""Free-tier gate for StackSage self-serve CLI.

Without a valid STACKSAGE_LICENSE:
- Sort findings by estimated_monthly_savings_usd (desc)
- Keep top 50
- Add a banner message to the analysis dict showing hidden count + estimated waste
- Remove remediation plan (paid only)
- Mark mode = "free"
"""

from __future__ import annotations

import os
from typing import Any, Dict

FREE_TIER_LIMIT = 50
_LICENSE_ENV_VAR = "STACKSAGE_LICENSE"


def is_licensed() -> bool:
    """Quick check: is a license key present in the environment?

    This does NOT validate the key — full validation happens via enforce_license().
    Used only to decide whether to apply the free-tier gate.
    """
    return bool(os.environ.get(_LICENSE_ENV_VAR, "").strip())


def apply_free_tier_gate(analysis: Dict[str, Any]) -> Dict[str, Any]:
    """Apply the free-tier cap if no license is present.

    If licensed: returns analysis unchanged (mode = "paid").
    If not licensed:
    - Sorts findings by savings desc, keeps top FREE_TIER_LIMIT
    - Adds free_tier_banner with hidden count + estimated hidden waste
    - Removes remediation_plan
    - Sets mode = "free"

    Always returns the (possibly modified) analysis dict.
    """
    if is_licensed():
        analysis["free_tier"] = False
        return analysis

    findings = analysis.get("findings", [])
    total = len(findings)

    # Always mark as free tier, even if under the cap
    analysis["free_tier"] = True
    analysis["mode"] = "free"
    # Remove remediation plan — paid only
    analysis.pop("remediation_plan", None)

    if total <= FREE_TIER_LIMIT:
        # All findings visible — no banner needed
        analysis["free_tier_banner"] = None
        return analysis

    # Sort by savings desc, split into visible / hidden
    sorted_findings = sorted(
        findings,
        key=lambda f: float(f.get("estimated_monthly_savings_usd") or 0),
        reverse=True,
    )
    visible = sorted_findings[:FREE_TIER_LIMIT]
    hidden = sorted_findings[FREE_TIER_LIMIT:]

    hidden_savings = sum(
        float(f.get("estimated_monthly_savings_usd") or 0) for f in hidden
    )

    analysis["findings"] = visible
    analysis["free_tier_total_findings"] = total
    analysis["free_tier_hidden_count"] = len(hidden)
    analysis["free_tier_hidden_savings_usd"] = round(hidden_savings, 2)
    analysis["free_tier_banner"] = (
        f"Found {total} findings. Showing top {FREE_TIER_LIMIT} by estimated savings. "
        f"Estimated waste in hidden findings: ~${hidden_savings:,.0f}/mo. "
        f"Unlock all findings \u2192 stacksageai.com/pricing"
    )

    return analysis
