from __future__ import annotations

import hashlib
import hmac
import json
import os
import re
import threading
import time
from collections import deque
from html import escape
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, Literal
from urllib.parse import quote

from fastapi import Body, FastAPI, HTTPException, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field

from core import JourneyValidationError, RuntimeJourneyError, run_until_input, validate_journey
from catalog import ProductCatalog, fetch_terms_page, safe_slug
from database import Database
from integrations import (
    IntegrationError,
    WooCommerceIntegration,
    execute_integration_action,
    normalize_iran_phone,
)


BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static"
DATA_DIR = BASE_DIR / "data"
EXAMPLES_DIR = BASE_DIR / "examples"
APP_VERSION = "3.1.0"


def normalize_base_path(value: str | None) -> str:
    """Normalize the public cPanel application prefix (for example /bot)."""
    raw = (value or "").strip()
    if not raw or raw == "/":
        return ""
    normalized = "/" + raw.strip("/")
    if not re.fullmatch(r"/[A-Za-z0-9._~/-]+", normalized):
        raise RuntimeError("ARCO_BOT_BASE_PATH contains unsupported characters.")
    return normalized.rstrip("/")


APP_BASE_PATH = normalize_base_path(os.getenv("ARCO_BOT_BASE_PATH"))
APP_MODE = os.getenv("ARCO_APP_MODE", "all").strip().lower() or "all"
if APP_MODE not in {"all", "admin", "widget"}:
    raise RuntimeError("ARCO_APP_MODE must be all, admin or widget.")
db_setting = Path(os.getenv("ARCO_BOT_DB", "data/arcopet_bot.sqlite3")).expanduser()
DB_PATH = db_setting if db_setting.is_absolute() else BASE_DIR / db_setting
ADMIN_PASSWORD = os.getenv("ARCO_ADMIN_PASSWORD", "").strip()
PUBLIC_BASE_URL = os.getenv("ARCO_PUBLIC_BASE_URL", "").strip().rstrip("/")
if APP_MODE == "admin" and not ADMIN_PASSWORD:
    raise RuntimeError("ARCO_ADMIN_PASSWORD is required when ARCO_APP_MODE=admin.")
AUTH_SECRET = os.getenv("ARCO_SECRET_KEY", "").strip() or hashlib.sha256(
    (ADMIN_PASSWORD + "::arcopet-bot-phase2").encode("utf-8")
).hexdigest()
AUTH_COOKIE = "arcopet_bot_admin"
AUTH_MAX_AGE = max(900, int(os.getenv("ARCO_AUTH_MAX_AGE", "43200")))
allowed_origins_setting = os.getenv(
    "ARCO_BOT_ALLOWED_ORIGINS",
    "https://arcopet.com,https://www.arcopet.com,http://localhost,http://127.0.0.1",
)
ALLOWED_ORIGINS = [item.strip().rstrip("/") for item in allowed_origins_setting.split(",") if item.strip()]
TRUST_PROXY = os.getenv("ARCO_TRUST_PROXY", "0").strip().lower() in {"1", "true", "yes", "on"}
CLIENT_IP_HEADER = os.getenv("ARCO_CLIENT_IP_HEADER", "X-Forwarded-For").strip()
WIDGET_RATE_LIMIT = max(10, min(600, int(os.getenv("ARCO_WIDGET_RATE_LIMIT", "60"))))
WIDGET_MAX_BODY_BYTES = max(4096, min(262144, int(os.getenv("ARCO_WIDGET_MAX_BODY_BYTES", "32768"))))
db = Database(DB_PATH)
_widget_rate_buckets: dict[str, deque[float]] = {}
_widget_rate_lock = threading.Lock()

DEFAULT_WIDGET_SETTINGS: dict[str, Any] = {
    "enabled": True,
    "title": "دستیار آرکوپت",
    "subtitle": "پاسخ‌گوی آنلاین",
    "launcher_text": "چطور می‌تونم کمکتون کنم؟",
    "welcome_hint": "سلام 👋 برای راهنمایی اینجام.",
    "start_journey": "main_menu",
    "primary_color": "#6d5dfc",
    "position": "left",
    "theme": "light",
}


class JourneyPayload(BaseModel):
    definition: dict[str, Any]


class DuplicatePayload(BaseModel):
    key: str = Field(min_length=2, max_length=80, pattern=r"^[a-z0-9_]+$")
    name: str = Field(min_length=2, max_length=120)


class RuntimeStartPayload(BaseModel):
    mode: Literal["draft", "published"] = "draft"


class RuntimeAnswerPayload(BaseModel):
    value: Any


class WidgetRuntimeStartPayload(BaseModel):
    page_url: str | None = Field(default=None, max_length=2048)
    page_title: str | None = Field(default=None, max_length=300)
    visitor_id: str | None = Field(default=None, max_length=120)


class WidgetSettings(BaseModel):
    enabled: bool = True
    title: str = Field(min_length=2, max_length=80)
    subtitle: str = Field(min_length=2, max_length=100)
    launcher_text: str = Field(min_length=2, max_length=100)
    welcome_hint: str = Field(min_length=2, max_length=180)
    start_journey: str = Field(min_length=2, max_length=80, pattern=r"^[a-z0-9_]+$")
    primary_color: str = Field(pattern=r"^#[0-9A-Fa-f]{6}$")
    position: Literal["left", "right"] = "left"
    theme: Literal["light", "dark", "auto"] = "light"


class LoginPayload(BaseModel):
    password: str = Field(min_length=1, max_length=500)


class TaxonomyTermPayload(BaseModel):
    taxonomy: Literal["category", "tag", "brand"]
    slug: str = Field(min_length=1, max_length=160)
    name_fa: str = Field(min_length=1, max_length=120)
    aliases: list[str] = Field(default_factory=list, max_length=12)


def seed_examples() -> None:
    for path in sorted(EXAMPLES_DIR.glob("*.json")):
        import json

        definition = json.loads(path.read_text(encoding="utf-8"))
        result = validate_journey(definition, strict=True)
        try:
            db.create_journey(result["normalized"])
        except ValueError:
            # Another Passenger worker, or an earlier run, already seeded it.
            pass
    for key in ("main_menu", "food_finder", "order_tracking", "supplement_finder"):
        try:
            item = db.get_journey(key)
            if item["published_version"] is None:
                db.publish(key)
        except KeyError:
            pass


def initialize_app_data() -> None:
    """Initialize eagerly because WSGI adapters do not always run ASGI lifespan."""
    db.initialize()
    seed_examples()


initialize_app_data()


@asynccontextmanager
async def lifespan(_: FastAPI):
    yield


app = FastAPI(
    title="Arcopet Bot Phase 3",
    version=APP_VERSION,
    description="Journey Builder, website widget and secure WooCommerce actions.",
    lifespan=lifespan,
    root_path=APP_BASE_PATH,
    docs_url=None if APP_MODE == "widget" else "/docs",
    redoc_url=None if APP_MODE == "widget" else "/redoc",
    openapi_url=None if APP_MODE == "widget" else "/openapi.json",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=ALLOWED_ORIGINS,
    allow_credentials=False,
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["Content-Type"],
)


def effective_base_path(request: Request) -> str:
    request_base_path = normalize_base_path(str(request.scope.get("root_path", "")))
    return APP_BASE_PATH or request_base_path


def create_auth_token() -> str:
    expires = str(int(time.time()) + AUTH_MAX_AGE)
    signature = hmac.new(AUTH_SECRET.encode("utf-8"), expires.encode("ascii"), hashlib.sha256).hexdigest()
    return f"{expires}.{signature}"


def valid_auth_token(token: str | None) -> bool:
    if not token or "." not in token:
        return False
    expires, supplied_signature = token.split(".", 1)
    if not expires.isdigit() or int(expires) < int(time.time()):
        return False
    expected = hmac.new(AUTH_SECRET.encode("utf-8"), expires.encode("ascii"), hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, supplied_signature)


def current_widget_settings() -> WidgetSettings:
    stored = db.get_setting("widget", {})
    merged = {**DEFAULT_WIDGET_SETTINGS, **(stored if isinstance(stored, dict) else {})}
    return WidgetSettings.model_validate(merged)


def is_public_path(path: str) -> bool:
    return (
        path == "/login"
        or path == "/widget.js"
        or (path == "/api/health" and APP_MODE != "admin")
        or path.startswith("/api/auth/")
        or path.startswith("/api/widget/")
        or path.startswith("/static/")
    )


def path_allowed_for_mode(mode: str, path: str) -> bool:
    if mode == "widget":
        return path == "/api/health" or path == "/widget.js" or path.startswith("/api/widget/")
    if mode == "admin":
        return path != "/widget.js" and not path.startswith("/api/widget/")
    return True


def request_route_path(request: Request) -> str:
    route_path = str(request.scope.get("path", request.url.path))
    scope_root = normalize_base_path(str(request.scope.get("root_path", "")))
    if scope_root and route_path.startswith(scope_root):
        route_path = route_path[len(scope_root) :] or "/"
    return route_path


def widget_client_key(request: Request) -> str:
    client_value = request.client.host if request.client else "unknown"
    if TRUST_PROXY and CLIENT_IP_HEADER:
        forwarded = request.headers.get(CLIENT_IP_HEADER, "").strip()
        if forwarded:
            client_value = forwarded.split(",", 1)[0].strip()
    return hashlib.sha256((AUTH_SECRET + "|" + client_value).encode("utf-8")).hexdigest()


def widget_request_allowed(client_key: str, now: float | None = None) -> bool:
    current = time.monotonic() if now is None else now
    cutoff = current - 60
    with _widget_rate_lock:
        bucket = _widget_rate_buckets.setdefault(client_key, deque())
        while bucket and bucket[0] <= cutoff:
            bucket.popleft()
        if len(bucket) >= WIDGET_RATE_LIMIT:
            return False
        bucket.append(current)
        if len(_widget_rate_buckets) > 10000:
            stale_keys = [key for key, values in _widget_rate_buckets.items() if not values or values[-1] <= cutoff]
            for key in stale_keys:
                _widget_rate_buckets.pop(key, None)
        return True


@app.middleware("http")
async def protect_admin(request: Request, call_next):
    route_path = request_route_path(request)
    if not path_allowed_for_mode(APP_MODE, route_path):
        response = JSONResponse({"detail": "مسیر پیدا نشد."}, status_code=404)
    elif route_path.startswith("/api/widget/") and request.method in {"POST", "PUT", "PATCH"}:
        content_length = request.headers.get("content-length", "0")
        if content_length.isdigit() and int(content_length) > WIDGET_MAX_BODY_BYTES:
            response = JSONResponse({"detail": "حجم درخواست بیش از حد مجاز است."}, status_code=413)
        elif not widget_request_allowed(widget_client_key(request)):
            response = JSONResponse(
                {"detail": "تعداد درخواست‌ها بیش از حد مجاز است؛ کمی بعد دوباره تلاش کنید."},
                status_code=429,
                headers={"Retry-After": "60"},
            )
        else:
            response = await call_next(request)
    elif not ADMIN_PASSWORD or is_public_path(route_path) or valid_auth_token(request.cookies.get(AUTH_COOKIE)):
        response = await call_next(request)
    elif route_path.startswith("/api/"):
        response = JSONResponse({"detail": "ورود مدیریتی لازم است."}, status_code=401)
    else:
        base_path = effective_base_path(request)
        next_path = route_path if route_path != "/login" else "/"
        response = RedirectResponse(f"{base_path}/login?next={quote(next_path)}", status_code=303)

    response.headers.setdefault("X-Content-Type-Options", "nosniff")
    response.headers.setdefault("X-Frame-Options", "DENY")
    response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
    response.headers.setdefault("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
    return response


@app.exception_handler(JourneyValidationError)
async def journey_validation_handler(_, exc: JourneyValidationError):
    return JSONResponse(
        status_code=422,
        content={"detail": "Journey نامعتبر است.", "errors": exc.errors, "warnings": exc.warnings},
    )


@app.get("/api/health")
def health() -> dict[str, Any]:
    public_status = {
        "ok": True,
        "phase": 3,
        "version": APP_VERSION,
        "mode": APP_MODE,
    }
    if APP_MODE == "widget":
        return public_status
    return {
        **public_status,
        "database": str(DB_PATH.name),
        "journeys": db.count_journeys(),
        "events": db.event_count(),
        "base_path": APP_BASE_PATH,
        "public_base_url": PUBLIC_BASE_URL,
        "widget": current_widget_settings().enabled,
        "admin_auth": bool(ADMIN_PASSWORD),
        "woocommerce": WooCommerceIntegration().public_status()["configured"],
    }


@app.get("/api/phases")
def phases() -> list[dict[str, Any]]:
    return [
        {"number": 1, "name": "هسته بات", "status": "complete"},
        {"number": 2, "name": "ویجت سایت", "status": "complete"},
        {"number": 3, "name": "WooCommerce و Ronad", "status": "active"},
        {"number": 4, "name": "تحلیل و قیف", "status": "locked"},
        {"number": 5, "name": "AI و کارشناس", "status": "locked"},
    ]


@app.get("/api/journeys")
def list_journeys() -> list[dict[str, Any]]:
    return db.list_journeys()


@app.post("/api/journeys", status_code=201)
def create_journey(payload: JourneyPayload) -> dict[str, Any]:
    result = validate_journey(payload.definition, strict=True)
    try:
        return db.create_journey(result["normalized"])
    except ValueError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@app.get("/api/journeys/{journey_key}")
def get_journey(
    journey_key: str,
    mode: Literal["draft", "published"] = Query(default="draft"),
) -> dict[str, Any]:
    try:
        return db.get_journey(journey_key, mode=mode)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Journey پیدا نشد.") from exc


@app.put("/api/journeys/{journey_key}/draft")
def update_journey(journey_key: str, payload: JourneyPayload) -> dict[str, Any]:
    result = validate_journey(payload.definition, strict=False)
    fatal_codes = {
        "unsupported_schema",
        "missing_journey",
        "missing_field",
        "missing_nodes",
        "invalid_node",
        "missing_node_id",
        "duplicate_node_id",
    }
    fatal_errors = [error for error in result["errors"] if error["code"] in fatal_codes]
    if fatal_errors:
        raise JourneyValidationError(fatal_errors, result["warnings"])
    try:
        return db.update_draft(journey_key, result["normalized"])
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Journey پیدا نشد.") from exc
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc


@app.post("/api/journeys/{journey_key}/publish")
def publish_journey(journey_key: str) -> dict[str, Any]:
    try:
        current = db.get_journey(journey_key)
        validate_journey(current["definition"], strict=True)
        return db.publish(journey_key)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Journey پیدا نشد.") from exc


@app.post("/api/journeys/{journey_key}/duplicate", status_code=201)
def duplicate_journey(journey_key: str, payload: DuplicatePayload) -> dict[str, Any]:
    try:
        return db.duplicate_journey(journey_key, payload.key, payload.name)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Journey مبدأ پیدا نشد.") from exc
    except ValueError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@app.post("/api/import/validate")
def validate_import(definition: dict[str, Any] = Body(...)) -> dict[str, Any]:
    result = validate_journey(definition, strict=False)
    return {key: value for key, value in result.items() if key != "normalized"}


@app.post("/api/import", status_code=201)
def import_journey(
    definition: dict[str, Any] = Body(...),
    strategy: Literal["create", "new_draft"] = Query(default="create"),
) -> dict[str, Any]:
    result = validate_journey(definition, strict=True)
    key = str(result["normalized"]["journey"]["key"])
    try:
        if strategy == "new_draft":
            return db.update_draft(key, result["normalized"])
        return db.create_journey(result["normalized"])
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Journey مقصد برای Update پیدا نشد.") from exc
    except ValueError as exc:
        raise HTTPException(status_code=409, detail=str(exc)) from exc


@app.get("/api/journeys/{journey_key}/export")
def export_journey(journey_key: str) -> JSONResponse:
    try:
        item = db.get_journey(journey_key)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Journey پیدا نشد.") from exc
    return JSONResponse(
        item["definition"],
        headers={"Content-Disposition": f'attachment; filename="{journey_key}.json"'},
    )


def _load_runtime_journey(
    key: str, mode: str, version: int | None = None
) -> tuple[dict[str, Any], int]:
    item = db.get_journey(key, mode=mode, version=version)
    return item["definition"], int(item["version"])


def execute_runtime_action(action: str, inputs: dict[str, Any]) -> dict[str, Any]:
    if action != "catalog.search_products":
        return execute_integration_action(action, inputs)
    try:
        return {"ok": True, "data": ProductCatalog().search(inputs, db.list_terms())}
    except IntegrationError as exc:
        return {"ok": False, "error": {"code": exc.code, "message": exc.public_message}}


def safe_event_variables(variables: dict[str, Any]) -> dict[str, Any]:
    sanitized: dict[str, Any] = {}
    for key, value in variables.items():
        if re.search(r"phone|mobile|tel", str(key), flags=re.IGNORECASE):
            normalized = normalize_iran_phone(value)
            sanitized[key] = "***" + normalized[-4:] if len(normalized) >= 4 else "***"
        elif isinstance(value, dict):
            sanitized[key] = safe_event_variables(value)
        else:
            sanitized[key] = value
    return sanitized


def _advance_session(session: dict[str, Any], answer: Any = None) -> dict[str, Any]:
    try:
        definition = db.get_journey(
            session["journey_key"],
            version=int(session["version"]),
            mode=session["mode"],
        )["definition"]
        result = run_until_input(
            definition=definition,
            current_node=str(session["current_node"]),
            variables=session["variables"],
            stack=session["stack"],
            journey_key=session["journey_key"],
            version=int(session["version"]),
            answer=answer,
            load_journey=lambda key, version=None: _load_runtime_journey(
                key, session["mode"], version
            ),
            execute_action=execute_runtime_action,
        )
    except (KeyError, RuntimeJourneyError) as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    db.update_session(
        session["id"],
        journey_key=result.journey_key,
        version=result.version,
        current_node=result.node_id,
        variables=result.variables,
        stack=result.stack,
        status="completed" if result.status == "completed" else "active",
    )
    for message in result.messages:
        db.log_event(session["id"], "message_sent", message)
    for action in result.actions:
        db.log_event(session["id"], "action_executed", action)
    if result.prompt:
        db.log_event(session["id"], "input_requested", {"node_id": result.node_id, **result.prompt})
    if result.status == "completed":
        db.log_event(
            session["id"],
            "journey_completed",
            {"variables": safe_event_variables(result.variables)},
        )
    return {
        "session_id": session["id"],
        "status": result.status,
        "messages": result.messages,
        "prompt": result.prompt,
        "variables": result.variables,
        "journey_key": result.journey_key,
        "version": result.version,
    }


def safe_answer_event(session: dict[str, Any], value: Any) -> dict[str, Any]:
    variable = ""
    try:
        definition = db.get_journey(
            session["journey_key"],
            version=int(session["version"]),
            mode=session["mode"],
        )["definition"]
        node = next(
            (
                item
                for item in definition.get("nodes", [])
                if item.get("id") == session.get("current_node")
            ),
            {},
        )
        variable = str(node.get("save_to", ""))
    except KeyError:
        pass
    logged_value = value
    if re.search(r"phone|mobile|tel", variable, flags=re.IGNORECASE):
        normalized = normalize_iran_phone(value)
        logged_value = "***" + normalized[-4:] if len(normalized) >= 4 else "***"
    return {"value": logged_value, "variable": variable}


@app.post("/api/runtime/{journey_key}/start")
def start_runtime(journey_key: str, payload: RuntimeStartPayload) -> dict[str, Any]:
    try:
        item = db.get_journey(journey_key, mode=payload.mode)
    except KeyError as exc:
        detail = "نسخه منتشرشده وجود ندارد." if payload.mode == "published" else "Journey پیدا نشد."
        raise HTTPException(status_code=404, detail=detail) from exc
    session = db.create_session(journey_key, payload.mode, item["definition"], int(item["version"]))
    return _advance_session(session)


@app.post("/api/runtime/sessions/{session_id}/answer")
def answer_runtime(session_id: str, payload: RuntimeAnswerPayload) -> dict[str, Any]:
    try:
        session = db.get_session(session_id)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Session پیدا نشد.") from exc
    if session["status"] == "completed":
        raise HTTPException(status_code=409, detail="این Session قبلاً تمام شده است.")
    db.log_event(session_id, "answer_received", safe_answer_event(session, payload.value))
    return _advance_session(session, payload.value)


@app.get("/api/admin/widget")
def get_widget_settings() -> dict[str, Any]:
    return current_widget_settings().model_dump()


@app.put("/api/admin/widget")
def update_widget_settings(payload: WidgetSettings) -> dict[str, Any]:
    try:
        db.get_journey(payload.start_journey, mode="published")
    except KeyError as exc:
        raise HTTPException(status_code=400, detail="Journey شروع باید یک نسخه Published داشته باشد.") from exc
    settings = payload.model_dump()
    db.set_setting("widget", settings)
    return settings


@app.get("/api/admin/integrations/woocommerce")
def woocommerce_status() -> dict[str, Any]:
    return WooCommerceIntegration().public_status()


@app.post("/api/admin/integrations/woocommerce/test")
def test_woocommerce_connection() -> dict[str, Any]:
    try:
        return WooCommerceIntegration().test_connection()
    except IntegrationError as exc:
        raise HTTPException(status_code=exc.status_code, detail=exc.public_message) from exc


@app.post("/api/admin/integrations/woocommerce/install-order-tracking")
def install_order_tracking_journey() -> dict[str, Any]:
    definition = json.loads((EXAMPLES_DIR / "03-order-tracking.json").read_text(encoding="utf-8"))
    normalized = validate_journey(definition, strict=True)["normalized"]
    try:
        db.get_journey("order_tracking")
    except KeyError:
        return db.create_journey(normalized)
    return db.update_draft("order_tracking", normalized)


@app.get("/api/admin/catalog/terms")
def list_catalog_terms(taxonomy: Literal["category", "tag", "brand"] | None = None) -> list[dict[str, Any]]:
    return db.list_terms(taxonomy)


@app.put("/api/admin/catalog/terms")
def save_catalog_term(payload: TaxonomyTermPayload) -> dict[str, Any]:
    try:
        slug = safe_slug(payload.slug)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from exc
    name = payload.name_fa.strip()
    aliases = list(dict.fromkeys(alias.strip() for alias in payload.aliases if alias.strip()))
    if not name or any(len(alias) > 120 for alias in aliases):
        raise HTTPException(status_code=422, detail="عنوان یا مترادف معتبر نیست.")
    return db.save_term(payload.taxonomy, slug, name, aliases)


@app.post("/api/admin/catalog/import")
def import_catalog_terms(payload: list[TaxonomyTermPayload] = Body(...)) -> dict[str, int]:
    if not payload or len(payload) > 1000:
        raise HTTPException(status_code=422, detail="بین ۱ تا ۱۰۰۰ اصطلاح ارسال کنید.")
    prepared: list[dict[str, Any]] = []
    seen = set()
    for item in payload:
        try:
            slug = safe_slug(item.slug)
        except ValueError as exc:
            raise HTTPException(status_code=422, detail=str(exc)) from exc
        name = item.name_fa.strip()
        aliases = list(dict.fromkeys(alias.strip() for alias in item.aliases if alias.strip()))
        if not name or any(len(alias) > 120 for alias in aliases):
            raise HTTPException(status_code=422, detail="عنوان یا مترادف معتبر نیست.")
        if (item.taxonomy, slug) in seen:
            raise HTTPException(status_code=422, detail="slug تکراری در فایل وجود دارد.")
        seen.add((item.taxonomy, slug))
        prepared.append({"taxonomy": item.taxonomy, "slug": slug, "name_fa": name, "aliases": aliases})
    return {"imported": db.import_terms(prepared)}


@app.delete("/api/admin/catalog/terms/{taxonomy}/{slug}")
def delete_catalog_term(taxonomy: Literal["category", "tag", "brand"], slug: str) -> dict[str, bool]:
    try:
        db.delete_term(taxonomy, slug)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="اصطلاح پیدا نشد.") from exc
    return {"ok": True}


@app.post("/api/admin/catalog/sync/{taxonomy}")
def sync_catalog_terms(taxonomy: Literal["category", "tag", "brand"], page: int = Query(default=1, ge=1, le=100)) -> dict[str, Any]:
    try:
        terms, has_more = fetch_terms_page(taxonomy, page)
    except IntegrationError as exc:
        if taxonomy == "brand" and exc.code == "taxonomy_not_found":
            raise HTTPException(status_code=404, detail="API برند WooCommerce در این فروشگاه فعال نیست؛ برندها را دستی ثبت کنید.") from exc
        raise HTTPException(status_code=exc.status_code, detail=exc.public_message) from exc
    db.sync_terms(taxonomy, terms)
    return {"imported": len(terms), "next_page": page + 1 if has_more and page < 100 else None}


@app.post("/api/admin/catalog/test")
def test_catalog_search(filters: dict[str, Any] = Body(default_factory=dict)) -> dict[str, Any]:
    try:
        return ProductCatalog().search(filters, db.list_terms())
    except IntegrationError as exc:
        raise HTTPException(status_code=exc.status_code, detail=exc.public_message) from exc


@app.get("/api/widget/config")
def widget_config() -> JSONResponse:
    settings = current_widget_settings().model_dump()
    return JSONResponse(settings, headers={"Cache-Control": "no-store"})


@app.post("/api/widget/runtime/{journey_key}/start")
def start_widget_runtime(journey_key: str, payload: WidgetRuntimeStartPayload) -> dict[str, Any]:
    settings = current_widget_settings()
    if not settings.enabled:
        raise HTTPException(status_code=503, detail="ویجت موقتاً غیرفعال است.")
    if journey_key != settings.start_journey:
        raise HTTPException(status_code=404, detail="Journey عمومی پیدا نشد.")
    try:
        item = db.get_journey(journey_key, mode="published")
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="نسخه Published برای ویجت وجود ندارد.") from exc
    session = db.create_session(journey_key, "published", item["definition"], int(item["version"]))
    db.log_event(
        session["id"],
        "widget_opened",
        {key: value for key, value in payload.model_dump().items() if value},
    )
    return _advance_session(session)


@app.post("/api/widget/runtime/sessions/{session_id}/answer")
def answer_widget_runtime(session_id: str, payload: RuntimeAnswerPayload) -> dict[str, Any]:
    try:
        session = db.get_session(session_id)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Session ویجت پیدا نشد.") from exc
    if session["mode"] != "published":
        raise HTTPException(status_code=403, detail="این Session متعلق به ویجت عمومی نیست.")
    if session["status"] == "completed":
        raise HTTPException(status_code=409, detail="این مکالمه قبلاً تمام شده است.")
    db.log_event(session_id, "answer_received", safe_answer_event(session, payload.value))
    return _advance_session(session, payload.value)


@app.get("/api/widget/runtime/sessions/{session_id}")
def resume_widget_runtime(session_id: str) -> dict[str, Any]:
    try:
        session = db.get_session(session_id)
    except KeyError as exc:
        raise HTTPException(status_code=404, detail="Session ویجت پیدا نشد.") from exc
    if session["mode"] != "published":
        raise HTTPException(status_code=403, detail="این Session عمومی نیست.")
    history: list[dict[str, Any]] = []
    prompt: dict[str, Any] | None = None
    for event in db.get_session_events(session_id):
        payload = event["payload"]
        if event["event_type"] == "message_sent":
            history.append({"role": "bot", "text": str(payload.get("text", "")),
                            "products": payload.get("products", []) if payload.get("type") == "products" else []})
        elif event["event_type"] == "answer_received":
            history.append({"role": "user", "text": str(payload.get("value", ""))})
            prompt = None
        elif event["event_type"] == "input_requested":
            prompt = payload
        elif event["event_type"] == "journey_completed":
            prompt = None
    return {
        "session_id": session["id"],
        "status": session["status"],
        "messages": [],
        "history": history,
        "prompt": prompt,
        "variables": session["variables"],
        "journey_key": session["journey_key"],
        "version": session["version"],
    }


@app.get("/api/auth/status")
def auth_status(request: Request) -> dict[str, bool]:
    return {
        "required": bool(ADMIN_PASSWORD),
        "authenticated": not ADMIN_PASSWORD or valid_auth_token(request.cookies.get(AUTH_COOKIE)),
    }


@app.post("/api/auth/login")
def login(payload: LoginPayload, request: Request) -> JSONResponse:
    if not ADMIN_PASSWORD or not hmac.compare_digest(payload.password, ADMIN_PASSWORD):
        raise HTTPException(status_code=401, detail="رمز عبور صحیح نیست.")
    response = JSONResponse({"ok": True})
    forwarded_proto = request.headers.get("x-forwarded-proto", request.url.scheme).split(",")[0].strip()
    response.set_cookie(
        AUTH_COOKIE,
        create_auth_token(),
        max_age=AUTH_MAX_AGE,
        httponly=True,
        secure=forwarded_proto == "https",
        samesite="strict",
        path=effective_base_path(request) or "/",
    )
    return response


@app.post("/api/auth/logout")
def logout(request: Request) -> JSONResponse:
    response = JSONResponse({"ok": True})
    response.delete_cookie(AUTH_COOKIE, path=effective_base_path(request) or "/")
    return response


@app.get("/widget.js", include_in_schema=False)
def widget_script() -> FileResponse:
    return FileResponse(
        STATIC_DIR / "widget.js",
        media_type="application/javascript; charset=utf-8",
        headers={"Cache-Control": "public, max-age=300"},
    )


@app.get("/guide/journey-builder", include_in_schema=False)
def journey_builder_guide() -> FileResponse:
    return FileResponse(
        BASE_DIR / "JOURNEY_BUILDER_GUIDE_FA.md",
        media_type="text/markdown; charset=utf-8",
        filename="Arcopet-Journey-Builder-Guide-FA.md",
    )


app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")


@app.get("/login", include_in_schema=False)
def login_page(request: Request):
    base_path = effective_base_path(request)
    if not ADMIN_PASSWORD or valid_auth_token(request.cookies.get(AUTH_COOKIE)):
        return RedirectResponse(f"{base_path}/", status_code=303)
    template = (STATIC_DIR / "login.html").read_text(encoding="utf-8")
    content = template.replace("{{ARCO_BOT_BASE_PATH}}", escape(base_path, quote=True))
    return HTMLResponse(content, headers={"Cache-Control": "no-store"})


@app.get("/", include_in_schema=False)
def panel(request: Request) -> HTMLResponse:
    # Passenger normally exposes the mounted URI as SCRIPT_NAME/root_path.
    # The environment variable is a reliable fallback for shared cPanel hosts.
    base_path = effective_base_path(request)
    template = (STATIC_DIR / "index.html").read_text(encoding="utf-8")
    content = template.replace("{{ARCO_BOT_BASE_PATH}}", escape(base_path, quote=True))
    return HTMLResponse(content, headers={"Cache-Control": "no-store"})
