"""租户状态API — CMA系统切换公司时记录当前tenant，供项目Bot分发A2A任务"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.models import SystemConfig, Entity

router = APIRouter(prefix="/api/cma/tenant", tags=["多租户"])

TENANT_KEY = "current_tenant"

class TenantSwitchRequest(BaseModel):
    entity_id: int
    source: str = "cma-system"


def _tenant_name(entity_id: int) -> str:
    """entity_id → tenant_id"""
    return "company_b" if entity_id == 2 else "company_a"


@router.get("/current")
def get_current_tenant(db: Session = Depends(get_db)):
    """查询当前租户"""
    cfg = db.query(SystemConfig).filter(SystemConfig.config_key == TENANT_KEY).first()
    if cfg and cfg.config_value:
        import json
        try:
            return json.loads(cfg.config_value)
        except:
            pass
    return {"tenant_id": "company_a", "entity_id": 1, "name": "陕西酣客文化传媒"}


@router.post("/switch")
def switch_tenant(data: TenantSwitchRequest, db: Session = Depends(get_db)):
    """切换当前租户（CMA前端企业切换器调用）"""
    ent = db.query(Entity).filter(Entity.id == data.entity_id).first()
    if not ent:
        raise HTTPException(404, "企业不存在")

    import json
    state = {
        "tenant_id": _tenant_name(data.entity_id),
        "entity_id": data.entity_id,
        "name": ent.name,
        "short_name": ent.short_name,
        "source": data.source,
        "switched_at": __import__("datetime").datetime.now().isoformat(),
    }

    cfg = db.query(SystemConfig).filter(SystemConfig.config_key == TENANT_KEY).first()
    if cfg:
        cfg.config_value = json.dumps(state, ensure_ascii=False)
    else:
        db.add(SystemConfig(
            config_key=TENANT_KEY,
            config_value=json.dumps(state, ensure_ascii=False),
            description="当前租户状态（CMA企业切换联动）",
        ))
    db.commit()

    return {"success": True, "current": state}
