import http from 'node:http';
import { createHash, randomBytes } from 'node:crypto';
import { appendFile } from 'node:fs/promises';

// Single-account lab runner. Authorization codes and tokens stay in memory.
const tenant = process.env.LAB_TENANT_ID;
const app = process.env.LAB_CLIENT_ID;
const account = process.env.LAB_PILOT_UPN?.trim().toLowerCase();
const guid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
if (!guid.test(tenant) || !guid.test(app) || !account?.includes('@')) throw Error('Set LAB_TENANT_ID, LAB_CLIENT_ID and LAB_PILOT_UPN first.');
const authority = 'https://login.microsoftonline.com/' + tenant + '/oauth2/v2.0/';
const base = 'http://localhost:61741';
const redirect = base + '/callback';
const pending = new Map();
const results = new Map();
const esc = (s) => String(s).replace(/[&<>"']/g, x => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[x]));
const id = () => randomBytes(32).toString('base64url');
const startNonce = id();
function page(res, heading, content) {
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  res.end('<!doctype html><html lang="en"><meta charset="utf-8"><title>Consent lab</title><style>body{max-width:720px;margin:8vh auto;padding:32px;font:19px/1.6 system-ui;color:#172e45}small{color:#286766}h1{line-height:1.15}dt{font-weight:650}dd{margin:0 0 14px}button{font:inherit;padding:.4em .8em}</style><small>LOCAL LAB CLIENT · TSC Consent Lab - Profile Reader</small><h1>'+esc(heading)+'</h1>'+content+'</html>');
}
function go(res,url){res.writeHead(303,{Location:url});res.end();}
async function completed(res,record){
  record.utc=new Date().toISOString();
  const key=id();
  results.set(key,record);
  await appendFile(new URL('./consent-pilot-observations.jsonl',import.meta.url),JSON.stringify(record)+'\n');
  go(res,'/result/'+key);
}
async function handle(req,res){
  res.setHeader('Cache-Control','no-store');
  res.setHeader('Referrer-Policy','no-referrer');
  res.setHeader('X-Content-Type-Options','nosniff');
  if(!['localhost:61741','127.0.0.1:61741'].includes(req.headers.host)){res.writeHead(400);return res.end();}
  const path=new URL(req.url,base).pathname;
  if(req.method==='GET' && path==='/'){
    return page(res,'Pilot sign-in','<p>Request Microsoft Graph User.Read for the pilot account, then read only its own profile. Each run starts a fresh OAuth flow.</p><form method="post" action="/start"><input type="hidden" name="nonce" value="'+startNonce+'"><button name="phase" value="initial">Start initial test</button> <button name="phase" value="after-revocation">Start post-revocation test</button></form>');
  }
  if(req.method==='GET' && path.startsWith('/result/')){
    const record=results.get(path.slice(8));
    if(!record){res.writeHead(404);return res.end();}
    return page(res,'Pilot observation','<dl>'+Object.entries(record).map(([k,v])=>'<dt>'+esc(k)+'</dt><dd>'+esc(v)+'</dd>').join('')+'</dl><a href="/">Return to lab</a>');
  }
  if(req.method!=='POST'||!['/start','/callback'].includes(path)){res.writeHead(404);return res.end();}
  let body='';
  for await(const chunk of req){body+=chunk;if(body.length>32768){res.writeHead(413);return res.end();}}
  const form=new URLSearchParams(body);
  if(path==='/start'){
    if(form.get('nonce')!==startNonce){res.writeHead(403);return res.end();}
    const phase=form.get('phase');
    if(!['initial','after-revocation'].includes(phase)){res.writeHead(400);return res.end();}
    const verifier=id(), state=id();
    pending.set(state,{verifier,phase,expires:Date.now()+900000});
    const args=new URLSearchParams({client_id:app,redirect_uri:redirect,response_type:'code',response_mode:'form_post',scope:'https://graph.microsoft.com/User.Read',login_hint:account,state,code_challenge_method:'S256',code_challenge:createHash('sha256').update(verifier).digest('base64url')});
    return go(res,authority+'authorize?'+args);
  }
  const item=pending.get(form.get('state'));
  pending.delete(form.get('state'));
  if(!item||item.expires<Date.now()){res.writeHead(400);return page(res,'Run expired','<p>Restart the test from the lab home page.</p>');}
  if(form.has('error'))return completed(res,{phase:item.phase,authorization:form.get('error'),code:(form.get('error_description')||'').match(/AADSTS\d+/)?.[0]||'not supplied',profileRead:'not attempted'});
  if(!form.has('code')){res.writeHead(400);return res.end();}
  const exchange=await fetch(authority+'token',{method:'POST',body:new URLSearchParams({client_id:app,code:form.get('code'),code_verifier:item.verifier,redirect_uri:redirect,grant_type:'authorization_code',scope:'https://graph.microsoft.com/User.Read'})});
  const token=await exchange.json();
  if(!exchange.ok)return completed(res,{phase:item.phase,exchange:exchange.status,error:token.error,profileRead:'not attempted'});
  const me=await fetch('https://graph.microsoft.com/v1.0/me?$select=userPrincipalName',{headers:{Authorization:'Bearer '+token.access_token}});
  const record=await me.json();
  return completed(res,{phase:item.phase,graphRequest:'GET /v1.0/me?$select=userPrincipalName',httpStatus:me.status,pilotAccountMatches:record.userPrincipalName?.toLowerCase()===account,scopes:token.scope || 'not returned'});
}
http.createServer((req,res)=>handle(req,res).catch(()=>{res.statusCode=502;page(res,'Request did not complete','<p>The local client could not complete the Microsoft request. No successful profile read has been recorded.</p>');})).listen(61741,'127.0.0.1',()=>console.log('Pilot client listening on '+base));
