# src/fmatch/saas/api/v2/column_mappings.py
"""Column mapping profiles API endpoints."""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
from datetime import datetime
import uuid

router = APIRouter(prefix="/api/v2/column-mappings", tags=["column-mappings"])


class MappingProfile(BaseModel):
    name: str
    object: str  # 'FileMatch' or 'Deduplicate'
    mappings: List[Dict[str, Any]]
    meta: Optional[Dict[str, Any]] = None


class ProfileResponse(BaseModel):
    id: str
    name: str
    object: str
    mappings: List[Dict[str, Any]]
    meta: Optional[Dict[str, Any]]
    created_at: datetime
    updated_at: datetime


# In-memory storage for demo (use database in production)
PROFILES_STORAGE: Dict[str, ProfileResponse] = {}


@router.post("/profiles")
async def save_mapping_profile(profile: MappingProfile):
    """Save a column mapping profile."""
    profile_id = str(uuid.uuid4())
    now = datetime.utcnow()

    profile_response = ProfileResponse(
        id=profile_id,
        name=profile.name,
        object=profile.object,
        mappings=profile.mappings,
        meta=profile.meta,
        created_at=now,
        updated_at=now,
    )

    PROFILES_STORAGE[profile_id] = profile_response

    return {
        "message": "Profile saved successfully",
        "profile_id": profile_id,
        "name": profile.name,
    }


@router.get("/profiles")
async def list_mapping_profiles():
    """List all saved column mapping profiles."""
    profiles = list(PROFILES_STORAGE.values())

    # Return summary list
    return [
        {
            "id": p.id,
            "name": p.name,
            "object": p.object,
            "created_at": p.created_at.isoformat(),
            "updated_at": p.updated_at.isoformat(),
            "mappings_count": len(p.mappings),
        }
        for p in profiles
    ]


@router.get("/profiles/{profile_id}")
async def get_mapping_profile(profile_id: str):
    """Get a specific column mapping profile."""
    if profile_id not in PROFILES_STORAGE:
        raise HTTPException(status_code=404, detail="Profile not found")

    return PROFILES_STORAGE[profile_id]


@router.delete("/profiles/{profile_id}")
async def delete_mapping_profile(profile_id: str):
    """Delete a column mapping profile."""
    if profile_id not in PROFILES_STORAGE:
        raise HTTPException(status_code=404, detail="Profile not found")

    profile = PROFILES_STORAGE.pop(profile_id)
    return {
        "message": "Profile deleted successfully",
        "profile_id": profile_id,
        "name": profile.name,
    }


@router.put("/profiles/{profile_id}")
async def update_mapping_profile(profile_id: str, profile: MappingProfile):
    """Update an existing column mapping profile."""
    if profile_id not in PROFILES_STORAGE:
        raise HTTPException(status_code=404, detail="Profile not found")

    existing = PROFILES_STORAGE[profile_id]

    # Update fields
    existing.name = profile.name
    existing.object = profile.object
    existing.mappings = profile.mappings
    existing.meta = profile.meta
    existing.updated_at = datetime.utcnow()

    return {
        "message": "Profile updated successfully",
        "profile_id": profile_id,
        "name": profile.name,
    }
