"""
Custom Paths Routes - Manage user-defined folder shortcuts for sharing links
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
import logging

from ..services import supabase_service

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/custom-paths", tags=["Custom Paths"])


# ==================== REQUEST MODELS ====================

class CustomPathCreate(BaseModel):
    ge_id: str
    lang: str
    custom_path: str


class CustomPathUpdate(BaseModel):
    custom_path: str


# ==================== ROUTES ====================

@router.get('')
def list_all_custom_paths():
    """
    Get all custom paths, sorted by ge_id ascending.

    Returns:
        {
            "success": true,
            "custom_paths": [
                {
                    "ge_id": "1000",
                    "lang": "DE",
                    "custom_path": "/folder/subfolder",
                    "created_at": "...",
                    "updated_at": "..."
                },
                ...
            ],
            "total": 10
        }
    """
    try:
        client = supabase_service.get_supabase_client()

        # Query all custom paths, ordered by ge_id ASC
        response = client.table("custom_paths").select(
            "*").order("ge_id", desc=False).execute()

        return {
            "success": True,
            "custom_paths": response.data or [],
            "total": len(response.data) if response.data else 0
        }

    except Exception as e:
        logger.error(f"Error listing custom paths: {e}")
        raise HTTPException(status_code=500, detail=f"Lỗi hệ thống: {e}")


@router.get('/{ge_id}')
def get_custom_path(ge_id: str, lang: Optional[str] = None):
    """
    Get custom path for a specific GE ID.

    Query params:
        lang: Optional language filter

    Returns:
        {
            "success": true,
            "custom_path": "/folder/subfolder",
            "ge_id": "1000",
            "lang": "DE"
        }
    """
    try:
        client = supabase_service.get_supabase_client()

        # Query with ge_id
        query = client.table("custom_paths").select("*").eq("ge_id", ge_id)

        # Add lang filter if provided
        if lang:
            query = query.eq("lang", lang.upper())

        response = query.execute()

        if not response.data or len(response.data) == 0:
            return {
                "success": True,
                "custom_path": None,
                "exists": False
            }

        record = response.data[0]  # type: ignore

        return {
            "success": True,
            "custom_path": record.get("custom_path") if isinstance(record, dict) else None,
            "ge_id": record.get("ge_id") if isinstance(record, dict) else None,
            "lang": record.get("lang") if isinstance(record, dict) else None,
            "exists": True,
            "created_at": record.get("created_at") if isinstance(record, dict) else None,
            "updated_at": record.get("updated_at") if isinstance(record, dict) else None
        }

    except Exception as e:
        logger.error(f"Error getting custom path: {e}")
        raise HTTPException(status_code=500, detail=f"Lỗi hệ thống: {e}")


@router.post('')
def create_or_update_custom_path(payload: CustomPathCreate):
    """
    Create or update custom path for a GE ID.
    Uses UPSERT logic (insert or update if exists).

    Body:
        {
            "ge_id": "1000",
            "lang": "DE",
            "custom_path": "/folder/subfolder"
        }

    Returns:
        {
            "success": true,
            "message": "Custom path saved",
            "is_new": true/false
        }
    """
    try:
        # Validate input
        if not payload.ge_id or not payload.lang or not payload.custom_path:
            raise HTTPException(
                status_code=400, detail="Thiếu thông tin: ge_id, lang, hoặc custom_path")

        client = supabase_service.get_supabase_client()

        # Check if exists
        existing = client.table("custom_paths").select(
            "*").eq("ge_id", payload.ge_id).execute()
        is_new = not existing.data or len(existing.data) == 0

        # Prepare data
        data = {
            "ge_id": payload.ge_id,
            "lang": payload.lang.upper(),
            "custom_path": payload.custom_path,
            "updated_at": "NOW()"
        }

        if is_new:
            # Insert new record
            response = client.table("custom_paths").insert(data).execute()
            message = "Custom path đã được thêm"
        else:
            # Update existing record
            response = client.table("custom_paths").update(
                data).eq("ge_id", payload.ge_id).execute()
            message = "Custom path đã được cập nhật"

        logger.debug(
            f"{'Created' if is_new else 'Updated'} custom path for {payload.ge_id} {payload.lang}: {payload.custom_path}")

        return {
            "success": True,
            "message": message,
            "is_new": is_new,
            "custom_path": payload.custom_path
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error saving custom path: {e}")
        raise HTTPException(status_code=500, detail=f"Lỗi hệ thống: {e}")


@router.delete('/{ge_id}')
def delete_custom_path(ge_id: str):
    """
    Delete custom path for a GE ID.

    Returns:
        {
            "success": true,
            "message": "Custom path deleted"
        }
    """
    try:
        client = supabase_service.get_supabase_client()

        # Check if exists
        existing = client.table("custom_paths").select(
            "*").eq("ge_id", ge_id).execute()

        if not existing.data or len(existing.data) == 0:
            raise HTTPException(
                status_code=404, detail="Custom path không tồn tại")

        # Delete
        client.table("custom_paths").delete().eq("ge_id", ge_id).execute()

        logger.debug(f"Deleted custom path for {ge_id}")

        return {
            "success": True,
            "message": "Custom path đã được xóa"
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting custom path: {e}")
        raise HTTPException(status_code=500, detail=f"Lỗi hệ thống: {e}")
