"""
Outfit Pairing Rules API
Provides endpoints to manage and retrieve product pairing logic
"""

from fastapi import APIRouter, HTTPException, Body
from typing import List, Optional
import json
import os
from pathlib import Path

router = APIRouter(prefix="/api/outfit-match-rules", tags=["Outfit Matching Rules"])

# Path to JSON data file
DATA_FILE = Path(__file__).parent.parent.parent.parent / "data" / "outfit_pairing_data.json"

def load_data():
    """Load pairing data from JSON file"""
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        # Return empty structure if file doesn't exist
        return {
            "product_genders": {},
            "pairings": [],
            "type_labels": {
                "t": "top",
                "b": "bottom",
                "o": "outerwear",
                "a": "accessory",
                "u": "underwear",
                "h": "home/other"
            }
        }

def save_data(data):
    """Save pairing data to JSON file"""
    DATA_FILE.parent.mkdir(parents=True, exist_ok=True)
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

@router.get("/pairings")
async def get_all_pairings(
    anchor: Optional[str] = None,
    target: Optional[str] = None,
    type: Optional[str] = None
):
    """
    Get all pairings or filter by anchor/target/type

    Args:
        anchor: Filter by anchor product name
        target: Filter by target product name
        type: Filter by pairing type (t/b/o/a/u/h)
    """
    data = load_data()
    pairings = data.get("pairings", [])

    # Apply filters
    if anchor:
        pairings = [p for p in pairings if p.get("anchor") == anchor]
    if target:
        pairings = [p for p in pairings if p.get("target") == target]
    if type:
        pairings = [p for p in pairings if p.get("type") == type]

    return {
        "success": True,
        "count": len(pairings),
        "pairings": pairings,
        "type_labels": data.get("type_labels", {})
    }

@router.get("/pairings/{anchor_name}")
async def get_pairings_by_anchor(anchor_name: str):
    """Get all pairings for a specific anchor product"""
    data = load_data()
    pairings = [p for p in data.get("pairings", []) if p.get("anchor") == anchor_name]

    return {
        "success": True,
        "anchor": anchor_name,
        "count": len(pairings),
        "pairings": pairings,
        "available_genders": data.get("product_genders", {}).get(anchor_name, [])
    }

@router.post("/pairings")
async def add_pairing(
    anchor: str = Body(..., embed=True),
    target: str = Body(..., embed=True),
    type: str = Body(..., embed=True)
):
    """
    Add a new pairing rule

    Args:
        anchor: Anchor product name
        target: Target product name to pair with
        type: Pairing type (t=top, b=bottom, o=outerwear, a=accessory, u=underwear, h=home/other)
    """
    data = load_data()

    # Validate type
    valid_types = data.get("type_labels", {}).keys()
    if type not in valid_types:
        raise HTTPException(status_code=400, detail=f"Invalid type. Must be one of: {', '.join(valid_types)}")

    # Check if pairing already exists
    existing = any(
        p["anchor"] == anchor and p["target"] == target and p["type"] == type
        for p in data.get("pairings", [])
    )

    if existing:
        raise HTTPException(status_code=409, detail="Pairing already exists")

    # Add new pairing
    new_pairing = {
        "anchor": anchor,
        "target": target,
        "type": type
    }
    data.setdefault("pairings", []).append(new_pairing)

    # Save to file
    save_data(data)

    return {
        "success": True,
        "message": "Pairing added successfully",
        "pairing": new_pairing
    }

@router.delete("/pairings")
async def delete_pairing(
    anchor: str = Body(..., embed=True),
    target: str = Body(..., embed=True),
    type: Optional[str] = Body(None, embed=True)
):
    """
    Delete a pairing rule

    Args:
        anchor: Anchor product name
        target: Target product name
        type: Optional type filter - if provided, only delete matching type
    """
    data = load_data()
    initial_count = len(data.get("pairings", []))

    # Filter out the pairing(s) to delete
    if type:
        data["pairings"] = [
            p for p in data.get("pairings", [])
            if not (p["anchor"] == anchor and p["target"] == target and p["type"] == type)
        ]
    else:
        data["pairings"] = [
            p for p in data.get("pairings", [])
            if not (p["anchor"] == anchor and p["target"] == target)
        ]

    deleted_count = initial_count - len(data["pairings"])

    if deleted_count == 0:
        raise HTTPException(status_code=404, detail="Pairing not found")

    # Save to file
    save_data(data)

    return {
        "success": True,
        "message": f"Deleted {deleted_count} pairing(s)",
        "deleted_count": deleted_count
    }

@router.get("/products")
async def get_all_products():
    """Get all product names with their gender assignments"""
    data = load_data()
    return {
        "success": True,
        "product_genders": data.get("product_genders", {}),
        "products": list(data.get("product_genders", {}).keys())
    }

@router.get("/types")
async def get_type_labels():
    """Get all pairing type labels"""
    data = load_data()
    return {
        "success": True,
        "type_labels": data.get("type_labels", {})
    }

@router.post("/sync")
async def sync_pairings(
    pairings: List[dict] = Body(..., embed=True)
):
    """
    Bulk sync/save multiple pairings at once

    Args:
        pairings: List of pairing objects {anchor, target, type}
    """
    data = load_data()

    # Validate all pairings
    valid_types = data.get("type_labels", {}).keys()
    for p in pairings:
        if "anchor" not in p or "target" not in p or "type" not in p:
            raise HTTPException(status_code=400, detail="Each pairing must have anchor, target, and type fields")
        if p["type"] not in valid_types:
            raise HTTPException(status_code=400, detail=f"Invalid type for pairing {p['anchor']}->{p['target']}")

    # Replace all pairings (or could merge - here we replace)
    data["pairings"] = pairings

    # Save to file
    save_data(data)

    return {
        "success": True,
        "message": f"Synced {len(pairings)} pairings",
        "count": len(pairings)
    }

@router.get("/export")
async def export_data():
    """Export full pairing data as JSON"""
    data = load_data()
    return data

@router.post("/import")
async def import_data(data: dict = Body(...)):
    """
    Import full pairing data (overwrites existing)

    Args:
        data: Full data structure with product_genders, pairings, type_labels
    """
    required_keys = ["product_genders", "pairings", "type_labels"]
    for key in required_keys:
        if key not in data:
            raise HTTPException(status_code=400, detail=f"Missing required key: {key}")

    # Save to file
    save_data(data)

    return {
        "success": True,
        "message": "Data imported successfully",
        "imported": {
            "products": len(data.get("product_genders", {})),
            "pairings": len(data.get("pairings", [])),
            "types": len(data.get("type_labels", {}))
        }
    }
