chrome.runtime.onInstalled.addListener(()=>{console.log("Coding Platform to GitHub extension installed")});chrome.runtime.onMessage.addListener((c,e,r)=>{if(c.action==="pushToGitHub")return P(c.data).then(a=>r({success:!0,result:a})).catch(a=>r({success:!1,error:a.message})),!0});async function P(c){const{problemData:e,githubConfig:r}=c,a=await chrome.storage.sync.get(["githubToken","githubUsername","githubRepo"]),l=r.token||a.githubToken,p=r.username||a.githubUsername,h=r.repo||a.githubRepo;if(!l||!p||!h)throw new Error("GitHub configuration incomplete. Please set token, username, and repository in the extension popup.");const $={python:"py",python3:"py",javascript:"js",typescript:"ts",java:"java",cpp:"cpp","c++":"cpp",c:"c",csharp:"cs","c#":"cs",go:"go",golang:"go",rust:"rs",ruby:"rb",swift:"swift",kotlin:"kt",scala:"scala",php:"php",sql:"sql",mysql:"sql",bash:"sh",shell:"sh",sh:"sh",pandas:"py",react:"jsx",unknown:"txt"},w=e.language.toLowerCase().replace(/\s+/g,"").replace(/[^a-z0-9]/g,""),u=$[w]||$[e.language.toLowerCase()]||"txt",j=(n,o)=>{if(!n)return"Problem";let t=n.trim();return o&&(t=t.replace(new RegExp(`^\\s*${o}\\s*\\.?\\s+`,"i"),""),t=t.replace(new RegExp(`^\\s*${o}\\.\\s*`,"i"),""),t=t.replace(new RegExp(`^\\s*${o}[^a-zA-Z]+`,"i"),"")),t=t.trim(),(!t||t.length===0)&&(t="Problem"),t=(C=>C.replace(/[^a-zA-Z0-9\s-]/g,"").trim().replace(/\s+/g,"_"))(t),t||(t="Problem"),t},g=e.problemNumber||"",b=j(e.title,g),k=g?`${g}_${b}.${u}`:`${b}.${u}`,m=`${e.platform}/${k}`,i={js:"//",ts:"//",java:"//",cpp:"//",c:"//",cs:"//",go:"//",rs:"//",swift:"//",kt:"//",scala:"//",php:"//",py:"#",rb:"#",sh:"#",sql:"--",txt:"//"}[u]||"//";let s="";if(s+=`${i} URL: ${e.url}
`,s+=`${i}
`,s+=`${i} Problem: ${e.title}
`,s+=`${i}
`,e.description&&e.description.trim().length>0){const n=e.description.split(`
`).map(o=>o.trimEnd()).filter(o=>o.length>0).join(`
`);s+=`${i} ${n.split(`
`).join(`
${i} `)}
`}s+=`
`,s+=`${i} Solution:
`,s+=e.code;let f=null;try{const n=await fetch(`https://api.github.com/repos/${p}/${h}/contents/${m}`,{headers:{Authorization:`token ${l}`,Accept:"application/vnd.github.v3+json"}});n.ok&&(f=(await n.json()).sha)}catch{}const x=`https://api.github.com/repos/${p}/${h}/contents/${m}`,y={message:`Add solution: ${e.title}`,content:btoa(unescape(encodeURIComponent(s))),branch:"main"};f&&(y.sha=f);const d=await fetch(x,{method:"PUT",headers:{Authorization:`token ${l}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify(y)});if(!d.ok){const n=await d.json();throw new Error(n.message||"Failed to push to GitHub")}return{message:"Successfully pushed to GitHub!",url:(await d.json()).content.html_url,filePath:m}}
