File size: 27,859 Bytes
6aecb2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
"""
Configuration management API for LandPPT
Supports per-user isolated configuration and system-level defaults
"""

from typing import Dict, Any, List, Optional
from fastapi import APIRouter, HTTPException, Depends, Request
from pydantic import BaseModel
import logging

from ..services.db_config_service import (
    get_db_config_service,
    DatabaseConfigService,
    get_user_llm_timeout_seconds,
)
from ..auth.middleware import get_current_admin_user, get_current_user_required
from ..database.models import User

logger = logging.getLogger(__name__)

router = APIRouter()


# Pydantic models
class ConfigUpdateRequest(BaseModel):
    config: Dict[str, Any]


class DefaultProviderRequest(BaseModel):
    provider: str


# ==================== User Config Endpoints ====================
# These endpoints allow users to manage their own configuration

@router.get("/api/config/user")
async def get_user_config(
    user: User = Depends(get_current_user_required)
):
    """Get current user's configuration (merged with system defaults, excluding admin-only categories)"""
    try:
        config_service = get_db_config_service()
        # Use get_all_config_for_user which filters admin-only categories for non-admins
        config = await config_service.get_all_config_for_user(user_id=user.id, is_admin=user.is_admin)
        return {
            "success": True,
            "config": config,
            "user_id": user.id,
            "is_admin": user.is_admin
        }
    except Exception as e:
        logger.error(f"Failed to get user configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to get user configuration")


@router.get("/api/config/user/{category}")
async def get_user_config_by_category(
    category: str,
    user: User = Depends(get_current_user_required)
):
    """Get user's configuration for a specific category"""
    try:
        config_service = get_db_config_service()
        schema = config_service.get_config_schema(include_admin_only=True)
        config = await config_service.get_all_config_for_user(user_id=user.id, is_admin=user.is_admin)
        config = {
            key: value
            for key, value in config.items()
            if schema.get(key, {}).get("category") == category
        }
        return {
            "success": True,
            "config": config,
            "category": category
        }
    except Exception as e:
        logger.error(f"Failed to get user configuration for category {category}: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to get configuration for category {category}")


@router.post("/api/config/user")
async def update_user_config(
    request: ConfigUpdateRequest,
    user: User = Depends(get_current_user_required)
):
    """Update current user's configuration"""
    try:
        config_service = get_db_config_service()

        # Prevent non-admin users from updating admin-only keys (which are stored at system scope).
        schema = config_service.get_config_schema(include_admin_only=True)
        admin_only_keys = {
            key for key, settings in schema.items()
            if settings.get("admin_only", False)
        }

        filtered_config = request.config
        if not user.is_admin:
            filtered_config = {
                key: value for key, value in (request.config or {}).items()
                if key not in admin_only_keys
            }

        success = await config_service.update_config(filtered_config, user_id=user.id)
        
        if success:
            return {
                "success": True,
                "message": "User configuration updated successfully"
            }
        else:
            raise HTTPException(status_code=500, detail="Failed to update user configuration")
            
    except Exception as e:
        logger.error(f"Failed to update user configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to update user configuration")


@router.post("/api/config/user/{category}")
async def update_user_config_by_category(
    category: str,
    request: ConfigUpdateRequest,
    user: User = Depends(get_current_user_required)
):
    """Update user's configuration for a specific category"""
    try:
        config_service = get_db_config_service()

        # Disallow updates to admin-only categories for non-admin users.
        if not user.is_admin and category in getattr(config_service, "ADMIN_ONLY_CATEGORIES", set()):
            raise HTTPException(status_code=403, detail="Not authorized to update this category")
        
        # Filter config to only include keys from the specified category
        schema = config_service.get_config_schema()
        filtered_config = {
            key: value
            for key, value in request.config.items()
            if key in schema
            and schema[key].get("category") == category
            and (user.is_admin or not schema[key].get("admin_only", False))
        }
        
        success = await config_service.update_config(filtered_config, user_id=user.id)
        
        if success:
            return {
                "success": True,
                "message": f"User configuration for {category} updated successfully"
            }
        else:
            raise HTTPException(status_code=500, detail=f"Failed to update configuration for {category}")
            
    except Exception as e:
        logger.error(f"Failed to update user configuration for category {category}: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to update configuration for {category}")


@router.post("/api/config/user/reset")
async def reset_user_config(
    user: User = Depends(get_current_user_required)
):
    """Reset user's configuration to system defaults"""
    try:
        config_service = get_db_config_service()
        success = await config_service.reset_user_config(user.id)
        
        if success:
            return {
                "success": True,
                "message": "User configuration reset to system defaults"
            }
        else:
            raise HTTPException(status_code=500, detail="Failed to reset user configuration")
            
    except Exception as e:
        logger.error(f"Failed to reset user configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to reset user configuration")


@router.post("/api/config/user/reset/{category}")
async def reset_user_config_by_category(
    category: str,
    user: User = Depends(get_current_user_required)
):
    """Reset user's configuration for a specific category to system defaults"""
    try:
        config_service = get_db_config_service()
        success = await config_service.reset_user_config(user.id, category=category)
        
        if success:
            return {
                "success": True,
                "message": f"User configuration for {category} reset to system defaults"
            }
        else:
            raise HTTPException(status_code=500, detail=f"Failed to reset configuration for {category}")
            
    except Exception as e:
        logger.error(f"Failed to reset user configuration for category {category}: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to reset configuration for {category}")


# Set default AI provider for user
@router.post("/api/config/default-provider")
async def set_user_default_provider(
    request: DefaultProviderRequest,
    user: User = Depends(get_current_user_required)
):
    """Set default AI provider for current user"""
    try:
        config_service = get_db_config_service()
        success = await config_service.update_config(
            {"default_ai_provider": request.provider},
            user_id=user.id
        )

        if success:
            return {
                "success": True,
                "message": f"Default provider set to {request.provider}",
                "provider": request.provider
            }
        else:
            raise HTTPException(status_code=500, detail="Failed to set default provider")

    except Exception as e:
        logger.error(f"Failed to set default provider: {e}")
        raise HTTPException(status_code=500, detail="Failed to set default provider")


@router.get("/api/config/current-provider")
async def get_user_current_provider(
    user: User = Depends(get_current_user_required)
):
    """Get current user's default AI provider"""
    try:
        config_service = get_db_config_service()
        provider = await config_service.get_config_value("default_ai_provider", user_id=user.id)
        
        return {
            "success": True,
            "current_provider": provider
        }
    except Exception as e:
        logger.error(f"Failed to get current provider: {e}")
        raise HTTPException(status_code=500, detail="Failed to get current provider")


@router.get("/api/config/schema")
async def get_config_schema(
    user: User = Depends(get_current_user_required)
):
    """Get configuration schema (excluding admin-only categories for non-admins)"""
    try:
        config_service = get_db_config_service()
        # Filter out admin-only categories for non-admin users
        schema = config_service.get_config_schema(include_admin_only=user.is_admin)
        return {
            "success": True,
            "schema": schema,
            "is_admin": user.is_admin
        }
    except Exception as e:
        logger.error(f"Failed to get configuration schema: {e}")
        raise HTTPException(status_code=500, detail="Failed to get configuration schema")


# ==================== Admin System Config Endpoints ====================
# These endpoints allow admins to manage system-wide default configuration

@router.get("/api/config/system")
async def get_system_config(
    user: User = Depends(get_current_admin_user)
):
    """Get system default configuration (admin only)"""
    try:
        config_service = get_db_config_service()
        await config_service.initialize_system_defaults()
        config = await config_service.get_all_config(user_id=None)  # None = system defaults
        return {
            "success": True,
            "config": config,
            "is_system": True
        }
    except Exception as e:
        logger.error(f"Failed to get system configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to get system configuration")


@router.post("/api/config/system")
async def update_system_config(
    request: ConfigUpdateRequest,
    user: User = Depends(get_current_admin_user)
):
    """Update system default configuration (admin only)"""
    try:
        config_service = get_db_config_service()
        success = await config_service.update_config(request.config, user_id=None)  # None = system
        
        if success:
            return {
                "success": True,
                "message": "System configuration updated successfully"
            }
        else:
            raise HTTPException(status_code=500, detail="Failed to update system configuration")
            
    except Exception as e:
        logger.error(f"Failed to update system configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to update system configuration")


@router.post("/api/config/system/{category}")
async def update_system_config_by_category(
    category: str,
    request: ConfigUpdateRequest,
    user: User = Depends(get_current_admin_user)
):
    """Update system configuration for a specific category (admin only)"""
    try:
        config_service = get_db_config_service()
        
        # Filter config to only include keys from the specified category
        schema = config_service.get_config_schema()
        filtered_config = {
            key: value
            for key, value in request.config.items()
            if key in schema and schema[key].get("category") == category
        }
        
        success = await config_service.update_config(filtered_config, user_id=None)
        
        if success:
            return {
                "success": True,
                "message": f"System configuration for {category} updated successfully"
            }
        else:
            raise HTTPException(status_code=500, detail=f"Failed to update system configuration for {category}")
            
    except Exception as e:
        logger.error(f"Failed to update system configuration for category {category}: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to update system configuration for {category}")


@router.post("/api/config/system/initialize")
async def initialize_system_config(
    user: User = Depends(get_current_admin_user)
):
    """Initialize system default configurations from schema defaults (admin only)"""
    try:
        config_service = get_db_config_service()
        count = await config_service.initialize_system_defaults()
        
        return {
            "success": True,
            "message": f"Initialized {count} system default configurations",
            "count": count
        }
    except Exception as e:
        logger.error(f"Failed to initialize system configurations: {e}")
        raise HTTPException(status_code=500, detail="Failed to initialize system configurations")


# ==================== Legacy Compatibility Endpoints ====================
# These maintain backward compatibility with old API calls

@router.get("/api/config/all")
async def get_all_config(
    user: User = Depends(get_current_user_required)
):
    """Get all configuration values for current user (legacy compatibility)"""
    try:
        config_service = get_db_config_service()

        # Backward-compatible promotion: if an admin previously saved a Tavily key as a user override,
        # promote it to system scope so other users can use research without configuring their own key.
        if getattr(user, "is_admin", False):
            try:
                system_tavily = await config_service.get_config_value("tavily_api_key", user_id=None)
                if not system_tavily and await config_service.is_user_override(user.id, "tavily_api_key"):
                    admin_config = await config_service.get_all_config(user_id=user.id)
                    admin_tavily = admin_config.get("tavily_api_key")
                    if admin_tavily:
                        await config_service.update_config({"tavily_api_key": admin_tavily}, user_id=None)
            except Exception:
                pass

        config = await config_service.get_all_config(user_id=user.id)
        
        # Filter out admin_only fields for non-admin users
        if not user.is_admin:
            schema = config_service.get_config_schema()
            admin_only_keys = [
                key for key, settings in schema.items()
                if settings.get("admin_only", False)
            ]
            for key in admin_only_keys:
                if key in config:
                    del config[key]

        # Redact sensitive values so system/admin defaults are never sent to the browser.
        # If a normal user has their own override, it's OK to return it to that user.
        tavily_value = config.get("tavily_api_key")
        tavily_configured = bool(str(tavily_value).strip()) if tavily_value is not None else False

        user_has_override = False
        if not getattr(user, "is_admin", False):
            try:
                user_has_override = await config_service.is_user_override(user.id, "tavily_api_key")
            except Exception:
                user_has_override = False

        if getattr(user, "is_admin", False) or not user_has_override:
            config.pop("tavily_api_key", None)

        config["tavily_api_key_configured"] = tavily_configured
        config["tavily_uses_admin_default"] = bool(tavily_configured and (not user.is_admin) and (not user_has_override))
        
        return {
            "success": True,
            "config": config
        }
    except Exception as e:
        logger.error(f"Failed to get configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to get configuration")


@router.post("/api/config/all")
async def update_all_config(
    request: ConfigUpdateRequest,
    user: User = Depends(get_current_user_required)
):
    """Update all configuration values for current user (legacy compatibility)"""
    try:
        config_service = get_db_config_service()

        # Prevent non-admin users from updating admin-only keys (which are stored at system scope).
        schema = config_service.get_config_schema(include_admin_only=True)
        admin_only_keys = {
            key for key, settings in schema.items()
            if settings.get("admin_only", False)
        }

        filtered_config = request.config
        if not user.is_admin:
            filtered_config = {
                key: value for key, value in (request.config or {}).items()
                if key not in admin_only_keys
            }

        # For sensitive settings, admins act as the "system default" so other users can use
        # the feature without configuring their own key.
        system_scoped = {}
        user_scoped = dict(filtered_config or {})
        if getattr(user, "is_admin", False) and "tavily_api_key" in user_scoped:
            system_scoped["tavily_api_key"] = user_scoped.pop("tavily_api_key")

        if system_scoped:
            ok = await config_service.update_config(system_scoped, user_id=None)
            if not ok:
                raise HTTPException(status_code=500, detail="Failed to update configuration")

        success = True
        if user_scoped:
            success = await config_service.update_config(user_scoped, user_id=user.id)
        
        if success:
            return {
                "success": True,
                "message": "Configuration updated successfully"
            }
        else:
            raise HTTPException(status_code=500, detail="Failed to update configuration")
            
    except Exception as e:
        logger.error(f"Failed to update configuration: {e}")
        raise HTTPException(status_code=500, detail="Failed to update configuration")


@router.get("/api/config/landppt/models")
async def get_landppt_models(
    user: User = Depends(get_current_user_required)
):
    """
    Fetch available models for LandPPT using system-level config.
    The API key is used on the backend and never exposed to the frontend.
    """
    import aiohttp
    
    try:
        config_service = get_db_config_service()
        
        # Get system-level config (user_id=None)
        api_key = await config_service.get_config_value("landppt_api_key", user_id=None)
        base_url = await config_service.get_config_value("landppt_base_url", user_id=None)
        
        if not api_key:
            return {
                "success": False,
                "error": "管理员尚未配置 LandPPT API Key"
            }
        
        if not base_url:
            base_url = "https://api.openai.com/v1"
        
        # Ensure base URL ends with /v1
        if not base_url.endswith('/v1'):
            base_url = base_url.rstrip('/') + '/v1'
        
        # Fetch models from the API
        models_url = f"{base_url}/models"
        timeout_seconds = await get_user_llm_timeout_seconds(user.id)
        
        async with aiohttp.ClientSession() as session:
            async with session.get(
                models_url,
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json"
                },
                timeout=aiohttp.ClientTimeout(total=timeout_seconds)
            ) as response:
                if response.status == 200:
                    data = await response.json()
                    models = data.get("data", [])
                    # Filter and sort models
                    model_ids = sorted([m.get("id", "") for m in models if m.get("id")])
                    return {
                        "success": True,
                        "models": model_ids
                    }
                else:
                    error_text = await response.text()
                    logger.error(f"Failed to fetch LandPPT models: {response.status} - {error_text}")
                    return {
                        "success": False,
                        "error": f"获取模型列表失败: HTTP {response.status}"
                    }
                    
    except Exception as e:
        logger.error(f"Failed to get LandPPT models: {e}")
        return {
            "success": False,
            "error": f"获取模型列表失败: {str(e)}"
        }


@router.post("/api/config/landppt/test")
async def test_landppt_provider(
    user: User = Depends(get_current_user_required)
):
    """
    Test LandPPT provider using system-level config.
    The API key is used on the backend and never exposed to the frontend.
    """
    import aiohttp
    
    try:
        config_service = get_db_config_service()
        
        # Get system-level config (user_id=None)
        api_key = await config_service.get_config_value("landppt_api_key", user_id=None)
        base_url = await config_service.get_config_value("landppt_base_url", user_id=None)
        model = await config_service.get_config_value("landppt_model", user_id=user.id)
        
        if not api_key:
            return {
                "success": False,
                "error": "管理员尚未配置 LandPPT API Key"
            }
        
        if not base_url:
            base_url = "https://api.openai.com/v1"
        
        if not model:
            model = "gpt-4o"
        
        # Ensure base URL ends with /v1
        if not base_url.endswith('/v1'):
            base_url = base_url.rstrip('/') + '/v1'
        
        # Test with a simple chat completion
        test_url = f"{base_url}/chat/completions"
        timeout_seconds = await get_user_llm_timeout_seconds(user.id)
        
        async with aiohttp.ClientSession() as session:
            async with session.post(
                test_url,
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json"
                },
                json={
                    "model": model,
                    "messages": [{"role": "user", "content": "Hello"}]
                },
                timeout=aiohttp.ClientTimeout(total=timeout_seconds)
            ) as response:
                if response.status == 200:
                    data = await response.json()
                    return {
                        "success": True,
                        "message": "LandPPT 提供者测试成功",
                        "model": model,
                        "response_preview": data.get("choices", [{}])[0].get("message", {}).get("content", "")[:50]
                    }
                else:
                    error_text = await response.text()
                    logger.error(f"LandPPT test failed: {response.status} - {error_text}")
                    return {
                        "success": False,
                        "error": f"测试失败: HTTP {response.status}"
                    }
                    
    except Exception as e:
        logger.error(f"Failed to test LandPPT provider: {e}")
        return {
            "success": False,
            "error": f"测试失败: {str(e)}"
        }


# Generic category routes last
@router.get("/api/config/{category}")
async def get_config_by_category(
    category: str,
    user: User = Depends(get_current_user_required)
):
    """Get configuration values by category for current user"""
    try:
        config_service = get_db_config_service()
        if not user.is_admin and category in getattr(config_service, "ADMIN_ONLY_CATEGORIES", set()):
            raise HTTPException(status_code=403, detail="Forbidden")

        config = await config_service.get_config_by_category(category, user_id=user.id)
        
        # Filter out admin_only fields for non-admin users
        if not user.is_admin:
            schema = config_service.get_config_schema()
            admin_only_keys = [
                key for key, settings in schema.items()
                if settings.get("admin_only", False)
            ]
            for key in admin_only_keys:
                if key in config:
                    del config[key]

        # Redact sensitive values so system/admin defaults are never sent to the browser.
        # If a normal user has their own override, it's OK to return it to that user.
        tavily_value = config.get("tavily_api_key")
        tavily_configured = bool(str(tavily_value).strip()) if tavily_value is not None else False

        user_has_override = False
        if not getattr(user, "is_admin", False):
            try:
                user_has_override = await config_service.is_user_override(user.id, "tavily_api_key")
            except Exception:
                user_has_override = False

        if getattr(user, "is_admin", False) or not user_has_override:
            config.pop("tavily_api_key", None)

        config["tavily_api_key_configured"] = tavily_configured
        config["tavily_uses_admin_default"] = bool(tavily_configured and (not user.is_admin) and (not user_has_override))
        
        return {
            "success": True,
            "config": config,
            "category": category
        }
    except Exception as e:
        logger.error(f"Failed to get configuration for category {category}: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to get configuration for category {category}")


@router.post("/api/config/{category}")
async def update_config_by_category(
    category: str,
    request: ConfigUpdateRequest,
    user: User = Depends(get_current_user_required)
):
    """Update configuration values for a specific category for current user"""
    try:
        config_service = get_db_config_service()
        if not user.is_admin and category in getattr(config_service, "ADMIN_ONLY_CATEGORIES", set()):
            raise HTTPException(status_code=403, detail="Forbidden")
         
        # Filter config to only include keys from the specified category
        schema = config_service.get_config_schema()
        filtered_config = {
            key: value
            for key, value in request.config.items()
            if key in schema and schema[key].get("category") == category
        }

        # For sensitive settings (e.g. Tavily key), admins set the system default.
        system_scoped = {}
        user_scoped = dict(filtered_config or {})
        if category == "generation_params" and getattr(user, "is_admin", False) and "tavily_api_key" in user_scoped:
            system_scoped["tavily_api_key"] = user_scoped.pop("tavily_api_key")

        if system_scoped:
            ok = await config_service.update_config(system_scoped, user_id=None)
            if not ok:
                raise HTTPException(status_code=500, detail=f"Failed to update configuration for {category}")

        success = True
        if user_scoped:
            success = await config_service.update_config(user_scoped, user_id=user.id)
        
        if success:
            return {
                "success": True,
                "message": f"Configuration for {category} updated successfully"
            }
        else:
            raise HTTPException(status_code=500, detail=f"Failed to update configuration for {category}")
            
    except Exception as e:
        logger.error(f"Failed to update configuration for category {category}: {e}")
        raise HTTPException(status_code=500, detail=f"Failed to update configuration for {category}")