"""License / trial guard checks — single entry point for plan limits."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

from . import state
from .plans import PlanLimits, limits_for_mode


@dataclass(frozen=True)
class GuardResult:
    allowed: bool
    code: str = ""
    message: str = ""


def _limits() -> PlanLimits:
    return limits_for_mode(state.get_mode())


def check_new_project(current_project_count: int) -> GuardResult:
    limits = _limits()
    if limits.max_projects is None:
        return GuardResult(True)
    if current_project_count >= limits.max_projects:
        return GuardResult(
            False,
            "trial_max_projects",
            f"試用版最多 {limits.max_projects} 個專案。購買 PhotoPick 可建立更多專案。",
        )
    return GuardResult(True)


def check_import_photo(current_photo_count: int, importing_new: bool = True) -> GuardResult:
    limits = _limits()
    if limits.max_photos_per_project is None:
        return GuardResult(True)
    if not importing_new:
        return GuardResult(True)
    if current_photo_count >= limits.max_photos_per_project:
        return GuardResult(
            False,
            "trial_max_photos",
            f"試用版本專案最多 {limits.max_photos_per_project} 張照片。購買 PhotoPick 可匯入更多。",
        )
    return GuardResult(True)


def check_batch_rename() -> GuardResult:
    if _limits().batch_rename_enabled:
        return GuardResult(True)
    return GuardResult(
        False,
        "trial_batch_rename",
        "試用版不包含批次重新命名。購買 PhotoPick 即可解鎖。",
    )


def check_batch_delete() -> GuardResult:
    if _limits().batch_delete_enabled:
        return GuardResult(True)
    return GuardResult(
        False,
        "trial_batch_delete",
        "試用版不包含批次移至垃圾桶。購買 PhotoPick 即可解鎖。",
    )


def check_export() -> GuardResult:
    if _limits().export_enabled:
        return GuardResult(True)
    return GuardResult(
        False,
        "trial_export",
        "試用版不包含轉檔匯出。購買 PhotoPick 即可解鎖。",
    )


def check_defect_detection() -> GuardResult:
    if _limits().defect_detection_enabled:
        return GuardResult(True)
    return GuardResult(
        False,
        "trial_defect_detection",
        "試用版不包含失焦／手震偵測。購買 PhotoPick 即可解鎖。",
    )


def check_exposure_detection() -> GuardResult:
    if _limits().exposure_detection_enabled:
        return GuardResult(True)
    return GuardResult(
        False,
        "trial_exposure_detection",
        "試用版不包含曝光偵測。購買 PhotoPick 即可解鎖。",
    )


def check_editing() -> GuardResult:
    if _limits().editing_enabled:
        return GuardResult(True)
    return GuardResult(
        False,
        "trial_editing",
        "試用版不包含裁切／水平校正。購買 PhotoPick 即可解鎖。",
    )


def check_quality_rescan(project_id: Optional[int], *, force: bool) -> GuardResult:
    """Manual full rescan (force=true). Import-time per-photo quality is always allowed."""
    if not force:
        return GuardResult(True)

    limits = _limits()
    if limits.quality_rescan_max_per_project is None:
        return GuardResult(True)
    if project_id is None:
        return GuardResult(True)

    used = state.quality_rescan_count(project_id)
    if used >= limits.quality_rescan_max_per_project:
        return GuardResult(
            False,
            "trial_quality_rescan",
            f"試用版每個專案只能手動重掃 {limits.quality_rescan_max_per_project} 次。"
            "購買 PhotoPick 可無限重掃。",
        )
    return GuardResult(True)


def record_quality_rescan_if_needed(project_id: Optional[int], *, force: bool) -> None:
    if not force or project_id is None:
        return
    if state.get_mode() == "licensed":
        return
    state.record_quality_rescan(project_id)


def raise_if_blocked(result: GuardResult) -> None:
    from fastapi import HTTPException

    if not result.allowed:
        raise HTTPException(
            status_code=403,
            detail={"code": result.code, "message": result.message},
        )
