import{format as R}from"util";import{CodeBuilder as q}from"../../helpers/code-builder.js";import{normalizeMimeType as N}from"../../../../utils.js";import{addIndentation as v,buildUrlExpression as I,printUrlVariablesDeclarations as P}from"../../helpers/code-helpers.js";import{HTTPSnippet as U}from"../../index.js";import{Lang as z}from"../../helpers/constants.js";import{MediaTypes as h}from"../../../../../constants.js";import{buildPythonDeviceAuthorizationCodeSnippet as M}from"../../helpers/device-auth-snippets.js";const S=function(t,c,{target:g,client:b}){const s=Object.assign({indent:"  "},c),{level:u=0}=s,e=new q({indentation:s.indent,variablesPrefix:s.variablesPrefix,lang:z.PYTHON}),x=t.securityOAuth2ExtraCalls?.some(a=>a.flowType==="deviceAuthorization");s.withComments&&Y(e),s.withImports&&(e.push("import requests"),x&&e.push("import time"),e.blank());let T=!1,r=t.allHeaders;if(t.securityOAuth2ExtraCalls?.length){const a=t.securityOAuth2ExtraCalls?.[0],o=new U(a).convert(g,b,{...s,withImports:!1,withComments:!1,variablesPrefix:"oauth2_"});e.push(o),e.blank(),a.flowType==="deviceAuthorization"&&M(e,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:u}),r=r||{},r.Authorization='"Bearer " + access_token',T=!0}P(t,e),e.push(`${e.var("url").toLowerCase()} = %s`,I(t,e)).blank();let C;Object.keys(t.queryObj||{}).length&&(C="query = "+O(t.queryObj,s.indent),e.push(C).blank());let p,m;const y=N(t.postData?.mimeType);if(t.postData)switch(y){case h.URL_ENCODED:p=t.postData.paramsObj?`${v(O(t.postData.paramsObj,s.indent),{level:0,firstLine:!1})}`:`"${t.postData.text}"`;break;case h.JSON:t.postData.jsonObj&&(p=v(O(t.postData.jsonObj,s.indent),{level:0,firstLine:!1}));break;case h.MULTIPART:const a=[],o=[];if(t.postData.params&&t.postData.params.length>0)for(const n of t.postData.params)n.fileName?o.push(`"${n.name}": ("${n.fileName}", open("${n.fileName}", "rb"))`):a.push(`"${n.name}": "${n.value}"`);else if(t.postData.text){const n=t.postData.text,f=n.match(/^--([^\r\n]+)/);if(f){const L=f[1];n.split(new RegExp(`--${L.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter($=>$.trim().length>0).forEach($=>{const w=$.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(w){const j=w[1],_=w[2],k=$.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),E=(k?k[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');_?o.push(`"${j}": ("${_}", open("${_}", "rb"))`):a.push(`"${j}": "${E}"`)}})}else{const L=t.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"');a.push(`"data": "${L}"`)}}if(o.length){const n=o.map(f=>`  ${f}`).join(`,
`);e.push(`files = {
${n}
}`).blank()}a.length&&(m=`data = {
${a.map(f=>`  ${f}`).join(`,
`)}
}`),m&&e.push(m).blank();break;default:t.postData.text&&(p=`'''
${v(t.postData.text.trim(),{level:1,indent:s.indent,firstLine:!0})}
'''`)}p&&e.push(`${e.var("payload").toLowerCase()} = %s`,p).blank();let i;const d=Object.keys(r).length,D=(a,o)=>a==="Authorization"&&T?o:`"${o}"`;if(d===1)for(i in r)e.push(`${e.var("headers").toLowerCase()} = {"${i}": ${D(i,r[i])}}`).blank();else if(d>1){let a=1;e.push(`${e.var("headers").toLowerCase()} = {`);for(i in r)a++!==d?e.push(1,`"${i}": ${D(i,r[i])},`):e.push(1,`"${i}": ${D(i,r[i])}`);e.push(0,"}").blank()}const A=t.method.toLowerCase();let l=R(`${e.var("response").toLowerCase()} = requests.${A}(${e.var("url").toLowerCase()}`);if(y===h.MULTIPART&&(m&&(l+=", data=data"),e.join().includes("files = {")&&(l+=", files=files")),p){const a=y===h.JSON?"json":"data";l+=`, ${a}=${e.var("payload").toLowerCase()}`}return d>0&&(l+=`, headers=${e.var("headers").toLowerCase()}`),C&&(l+=`, params=${e.var("query").toLowerCase()}`),t.basicAuth&&(l+=`, auth=('${t.basicAuth.username}','${t.basicAuth.password}')`),l+=")",e.push(l).blank(),t.allResponseCodes?.includes("204")?e.push("if response.status_code == 204:").push(u+1,'print("success")').push("else:").push(u+1,`${e.var("data").toLowerCase()} = ${e.var("response").toLowerCase()}.json()`).push(u+1,`print(${e.var("data").toLowerCase()})`):e.push(`${e.var("data").toLowerCase()} = ${e.var("response").toLowerCase()}.json()`).push(`print(${e.var("data").toLowerCase()})`),e.join()};var Z=S;function Y(t){t.push('"""'),t.push("Requires python >= 3"),t.blank(),t.push('Requires module "requests" >= 2.25.1'),t.push("See here for installation details:"),t.push("  https://requests.readthedocs.io/"),t.push('"""'),t.blank()}function O(t,c){return JSON.stringify(t,function(b,s){return b&&typeof s=="boolean"?s?"__REDOCLY_<True>__":"__REDOCLY_<False>__":s===null?"__REDOCLY_<None>__":s},c).replace(/"__REDOCLY_<(\w+)>__"/g,"$1")}export{Z as default};
