import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'

/**
 * GET /api/agent/script
 * Header: x-agent-token: agt_xxx
 *
 * Retorna o script Python do agente para download.
 * Autenticado via agent_token para evitar download não autorizado.
 */
export async function GET(req: NextRequest) {
  const agentToken = req.headers.get('x-agent-token') ?? ''

  if (!agentToken) {
    return new NextResponse('# Token ausente', { status: 401, headers: { 'Content-Type': 'text/plain' } })
  }

  const [rows] = await pool.execute<any[]>(
    "SELECT id FROM tenants WHERE agent_token = ? AND status = 'active' LIMIT 1",
    [agentToken],
  )
  if (!rows[0]) {
    return new NextResponse('# Token invalido', { status: 401, headers: { 'Content-Type': 'text/plain' } })
  }

  const script = `
#!/usr/bin/env python3
"""
ConsultarTI Agent - Sincronizacao Active Directory
Lê config.json na mesma pasta para token e base_url.
"""
import json, os, time, logging, socket
import requests

BASE_DIR   = os.path.dirname(os.path.abspath(__file__))
CONFIG     = os.path.join(BASE_DIR, "config.json")
LOG_FILE   = os.path.join(BASE_DIR, "agent.log")
POLL_INTERVAL = 30  # segundos

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler(LOG_FILE, encoding="utf-8"),
        logging.StreamHandler(),
    ],
)
log = logging.getLogger("agent")

def load_config():
    with open(CONFIG, encoding="utf-8") as f:
        return json.load(f)

def fetch_tasks(cfg):
    r = requests.get(
        f"{cfg['base_url']}/api/agent/tasks",
        headers={"x-agent-token": cfg["token"]},
        timeout=15,
    )
    r.raise_for_status()
    return r.json().get("tasks", [])

def report_task(cfg, task_id, status, result=None):
    requests.patch(
        f"{cfg['base_url']}/api/agent",
        json={"task_id": task_id, "status": status, "result": result},
        headers={"x-agent-token": cfg["token"]},
        timeout=15,
    )

def heartbeat(cfg):
    try:
        requests.post(
            f"{cfg['base_url']}/api/agent/heartbeat",
            json={"hostname": socket.gethostname()},
            headers={"x-agent-token": cfg["token"]},
            timeout=10,
        )
    except Exception:
        pass

def execute_task(task):
    import subprocess
    t    = task.get("type", "")
    data = task.get("payload", {})
    if isinstance(data, str):
        import json as _j
        data = _j.loads(data)

    if t == "create_user":
        cmd = [
            "powershell", "-Command",
            f"New-ADUser -Name '{data.get('display_name','')}' "
            f"-SamAccountName '{data.get('sam_account_name','')}' "
            f"-UserPrincipalName '{data.get('upn','')}' "
            f"-GivenName '{data.get('first_name','')}' "
            f"-Surname '{data.get('last_name','')}' "
            f"-EmailAddress '{data.get('email','')}' "
            f"-Department '{data.get('department','')}' "
            f"-Enabled {'$true' if data.get('enabled', True) else '$false'} "
            f"-AccountPassword (ConvertTo-SecureString '{data.get('password','')}' -AsPlainText -Force) "
            f"-ChangePasswordAtLogon {'$true' if data.get('must_change_password') else '$false'}"
        ]
    elif t == "update_user":
        cmd = [
            "powershell", "-Command",
            f"Set-ADUser -Identity '{data.get('sam_account_name','')}' "
            f"-DisplayName '{data.get('display_name','')}' "
            f"-EmailAddress '{data.get('email','')}' "
            f"-Department '{data.get('department','')}'"
        ]
    elif t == "delete_user":
        cmd = [
            "powershell", "-Command",
            f"Disable-ADAccount -Identity '{data.get('sam_account_name','')}'"
        ]
    elif t == "reset_password":
        cmd = [
            "powershell", "-Command",
            f"Set-ADAccountPassword -Identity '{data.get('sam_account_name','')}' "
            f"-NewPassword (ConvertTo-SecureString '{data.get('password','')}' -AsPlainText -Force) -Reset; "
            f"Set-ADUser -Identity '{data.get('sam_account_name','')}' -ChangePasswordAtLogon "
            f"{'$true' if data.get('must_change_password') else '$false'}"
        ]
    elif t == "create_group":
        cmd = [
            "powershell", "-Command",
            f"New-ADGroup -Name '{data.get('display_name','')}' "
            f"-SamAccountName '{data.get('sam_account_name','')}' "
            f"-GroupScope Global -GroupCategory Security"
        ]
    elif t == "add_group_member":
        cmd = [
            "powershell", "-Command",
            f"Add-ADGroupMember -Identity '{data.get('group_sam','')}' "
            f"-Members '{data.get('user_sam','')}'"
        ]
    elif t == "remove_group_member":
        cmd = [
            "powershell", "-Command",
            f"Remove-ADGroupMember -Identity '{data.get('group_sam','')}' "
            f"-Members '{data.get('user_sam','')}' -Confirm:$false"
        ]
    else:
        return {"error": f"Tarefa desconhecida: {t}"}

    result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
    if result.returncode != 0:
        raise Exception(result.stderr.strip() or "Erro PowerShell sem mensagem")
    return {"stdout": result.stdout.strip()}

def main():
    log.info("Agente ConsultarTI iniciado.")
    cfg = load_config()
    log.info(f"Conectado a {cfg['base_url']} | tenant {cfg['tenant_id']}")

    while True:
        try:
            heartbeat(cfg)
            tasks = fetch_tasks(cfg)
            for task in tasks:
                tid = task["id"]
                log.info(f"Executando tarefa #{tid}: {task.get('type')}")
                try:
                    result = execute_task(task)
                    report_task(cfg, tid, "done", result)
                    log.info(f"Tarefa #{tid} concluida.")
                except Exception as e:
                    report_task(cfg, tid, "error", {"error": str(e)})
                    log.error(f"Tarefa #{tid} falhou: {e}")
        except Exception as e:
            log.error(f"Erro no loop principal: {e}")

        time.sleep(POLL_INTERVAL)

if __name__ == "__main__":
    main()
`.trimStart()

  return new NextResponse(script, {
    status: 200,
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'no-store',
    },
  })
}
