# --- routers/config.py ---
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from netmiko import ConnectHandler
from shared import CMTS_DEVICE, cmts_config_lock

router = APIRouter()

class ConfigRequest(BaseModel):
    script: str
    host: str
    username: str
    password: str

@router.post("/cmts-config")
async def execute_cmts_config(req: ConfigRequest):
    # 使用非同步鎖，確保同一時間只有一個寫入任務執行
    async with cmts_config_lock:
        try:
            device = CMTS_DEVICE.copy()
            device.update({'host': req.host, 'username': req.username, 'password': req.password})
            
            # 過濾掉空行與註解 (! 開頭的行)
            commands = [cmd.strip() for cmd in req.script.splitlines() if cmd.strip() and not cmd.strip().startswith('!')]
            
            net_connect = ConnectHandler(**device)
            net_connect.send_command_timing("config")
            
            # 批次送出設定指令
            output = net_connect.send_config_set(commands, cmd_verify=False)
            
            net_connect.send_command_timing("exit")
            net_connect.disconnect()
            
            return {"status": "success", "data": output}
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"CMTS Config Error: {str(e)}")
