"""Local usage metering for MixLift free tier."""

import json
import logging
from datetime import datetime
from pathlib import Path

logger = logging.getLogger(__name__)

USAGE_FILE = Path.home() / ".mixlift" / "usage.json"


def check_and_increment(max_free_runs: int = 2) -> tuple[bool, str]:
    """Check if free tier run limit allows another run, and increment if so.

    Returns (allowed, message).
    """
    current_month = datetime.now().strftime("%Y-%m")

    # Load existing usage
    usage = {"month": current_month, "runs": 0}
    try:
        if USAGE_FILE.exists():
            usage = json.loads(USAGE_FILE.read_text())
            # Reset on new month
            if usage.get("month") != current_month:
                usage = {"month": current_month, "runs": 0}
    except Exception:
        usage = {"month": current_month, "runs": 0}

    if usage["runs"] >= max_free_runs:
        return False, (
            f"Free tier limit reached ({max_free_runs} analyses/month). "
            f"Upgrade to Growth ($299/mo) for unlimited analyses at https://mixlift.io/pricing"
        )

    # Increment and save
    usage["runs"] += 1
    try:
        USAGE_FILE.parent.mkdir(parents=True, exist_ok=True)
        USAGE_FILE.write_text(json.dumps(usage))
    except Exception as e:
        logger.warning(f"Could not save usage data: {e}")

    remaining = max_free_runs - usage["runs"]
    return True, f"Free tier: {usage['runs']}/{max_free_runs} analyses used this month ({remaining} remaining)"
