"""Settings API routes."""

from pathlib import Path
from fastapi import APIRouter, HTTPException

from ..models import SettingsRequest, SettingsResponse, ValidateKeyResponse
from ..config import load_config, save_config

router = APIRouter()


@router.get("/settings", response_model=SettingsResponse)
async def get_settings():
    """Get current application settings."""
    config = load_config()
    return SettingsResponse(
        openai_api_key_set=bool(config.openai_api_key),
        output_directory=config.output_directory
    )


@router.post("/settings", response_model=SettingsResponse)
async def update_settings(request: SettingsRequest):
    """Update application settings."""
    config = load_config()

    if request.openai_api_key is not None:
        config.openai_api_key = request.openai_api_key

    if request.output_directory is not None:
        # Validate directory path
        output_path = Path(request.output_directory)
        try:
            output_path.mkdir(parents=True, exist_ok=True)
            if not output_path.is_dir():
                raise HTTPException(status_code=400, detail="Invalid directory path")
        except PermissionError:
            raise HTTPException(status_code=400, detail="Permission denied for directory")
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Invalid path: {str(e)}")

        config.output_directory = str(output_path.absolute())

    save_config(config)

    return SettingsResponse(
        openai_api_key_set=bool(config.openai_api_key),
        output_directory=config.output_directory
    )


@router.post("/settings/validate-key", response_model=ValidateKeyResponse)
async def validate_api_key(request: SettingsRequest):
    """Validate an OpenAI API key."""
    if not request.openai_api_key:
        raise HTTPException(status_code=400, detail="API key is required")

    try:
        from openai import OpenAI
        client = OpenAI(api_key=request.openai_api_key)
        # Try a simple API call to validate the key
        client.models.list()
        return ValidateKeyResponse(valid=True, message="API key is valid")
    except Exception as e:
        return ValidateKeyResponse(valid=False, message=str(e))
