"use client";
import { useState } from "react";

function example() {
  const now = new Date();
  return `schema_version: '1.0'
mandate_id: example-mandate
run_id: example-run
principal: example-principal
agent_id: example-agent
objective: Read the status of one bounded API resource
issued_at: '${now.toISOString()}'
not_before: '${now.toISOString()}'
expires_at: '${new Date(now.getTime()+3600000).toISOString()}'
nonce: example-preflight-000001
claim_boundary: Every effectful action must pass through a guarded adapter.
rules:
  - rule_id: read-status
    effect: allow
    action: network.http
    resource: https://example.com/api/status
    methods: [GET]
    max_uses: 1
`;
}
type Result = {valid:boolean;manifest_sha256:string;authority_granted:boolean;findings:Array<{code:string;severity:string;message:string;rule_id:string|null}>;rules:Array<{rule_id:string;action:string;resource:string;max_uses:number|null}>;boundary:string};

export function ManifestInspector() {
  const [source,setSource]=useState('');
  const [result,setResult]=useState<Result|null>(null);
  const [error,setError]=useState('');
  const [busy,setBusy]=useState(false);
  async function inspect() {
    if (busy) return;
    setBusy(true);setError('');setResult(null);
    try {
      const response=await fetch('/api/inspect',{method:'POST',headers:{'Content-Type':'application/yaml'},body:source,signal:AbortSignal.timeout(15000)});
      const data=await response.json();
      if(!response.ok) throw new Error(data.error||'Inspection unavailable. Try the local CLI.');
      setResult(data);
    } catch(e) {setError(e instanceof Error?e.message:'Inspection failed.');}
    finally {setBusy(false);}
  }
  function download() {
    const url=URL.createObjectURL(new Blob([JSON.stringify(result,null,2)],{type:'application/json'}));
    const a=document.createElement('a');a.href=url;a.download='scopewrit-preflight.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
  }
  return <section className="shell manifest-workbench" id="inspect" aria-labelledby="inspect-title">
    <div><p className="kicker">WORKBENCH / UNSIGNED MANIFEST</p><h2 id="inspect-title">Inspect the scope<br/><em>before you sign.</em></h2><p>Find expired windows, invalid resources, and broad permissions. This preflight grants no authority.</p></div>
    <div className="manifest-grid"><div><div className="workbench-actions"><button type="button" onClick={()=>{setSource(example());setResult(null);setError('');}}>Load example</button><label className="file-button">Import YAML<input aria-label="Import manifest YAML" type="file" accept=".yaml,.yml,.json" onChange={async e=>{const file=e.target.files?.[0]; if(!file)return; if(file.size>262144){setError('Manifest exceeds 256 KiB.');return;}setSource(await file.text());setResult(null);e.target.value='';}}/></label></div><label htmlFor="manifest-source">Unsigned manifest</label><textarea id="manifest-source" value={source} onChange={e=>{setSource(e.target.value);setResult(null);}} placeholder="Load the example or paste your unsigned YAML manifest." spellCheck={false}/><button className="button button-primary" onClick={inspect} disabled={busy||!source.trim()}>{busy?'Inspecting…':'Inspect manifest →'}</button><p className="workbench-note">Submitted to the Cyberelf VPS for stateless inspection. For sensitive manifests, run <code>scopewrit inspect --manifest your-run.yaml</code> locally.</p></div><div className="manifest-result" aria-live="polite">{error?<p role="alert">{error}</p>:result?<><strong className={result.valid?'result-pass':'result-block'}>{result.valid?'PREFLIGHT VALID':'NEEDS CORRECTION'}</strong><p>Authority granted: <b>No</b></p><ul>{result.findings.length?result.findings.map((f,i)=><li key={i}><b>{f.severity.toUpperCase()} · {f.rule_id||f.code}</b><p>{f.message}</p></li>):<li>No static findings in this manifest.</li>}</ul><p>{result.rules.length} rule(s) inspected</p><code>{result.manifest_sha256}</code><p>{result.boundary}</p><button onClick={download}>Download preflight</button></>:<><strong>Check a manifest before committing to it.</strong><p>The result includes a digest, normalized resources, rule-level findings, and the remaining authorization boundary.</p></>}</div></div></section>;
}
