"""Create a native Word report from the adjacent, public synthetic fixture text.

Uses the Panes SDK and the signed-in desktop. The target directory must be new.
If a request is uncertain, inspect its directory and Word window before retrying.
No Office security, account, activation or machine-wide setting is changed.
"""
import argparse, json, time
from pathlib import Path, PureWindowsPath
from panes import Panes

def quote(value):
    return "'" + value.replace("'", "''") + "'"

def run(machine, directory):
    path = PureWindowsPath(directory)
    if path.drive.upper() != 'C:' or len(path.parts) < 3 or path.parts[1].lower() != 'work' or '..' in path.parts:
        raise ValueError('Choose a new task directory under C:\\work')
    directory = str(path)
    started = time.perf_counter()
    setup = machine.exec("$ErrorActionPreference='Stop';if(Test-Path -LiteralPath " + quote(directory) + "){throw 'Task directory already exists; inspect it before retrying'};New-Item -ItemType Directory -Path " + quote(directory) + "|Out-Null", desktop=True, timeout_s=20)
    if setup.exit_code != 0 or setup.timed_out:
        raise RuntimeError('Task directory was not created; inspect before retrying')
    body = Path(__file__).with_name('word-report-source.txt').read_text().strip().replace('\n', '\r')
    docx = str(path / 'expense-review.docx');pdf = str(path / 'expense-review.pdf')
    script = "$ErrorActionPreference='Stop';$clock=[Diagnostics.Stopwatch]::StartNew();$w=New-Object -ComObject Word.Application;$w.Visible=$true;$w.DisplayAlerts=0;$d=$w.Documents.Add();$d.Content.Text=" + quote(body)
    script += ";$d.Content.Font.Name='Aptos';$d.Content.Font.Size=11;$d.Paragraphs.Item(1).Range.Font.Size=24;$d.Paragraphs.Item(1).Range.Font.Bold=1;$d.PageSetup.TopMargin=45;$d.PageSetup.BottomMargin=45;$d.PageSetup.LeftMargin=50;$d.PageSetup.RightMargin=50;$d.SaveAs2(" + quote(docx) + ",16);$d.ExportAsFixedFormat(" + quote(pdf) + ",17);$d.Close(0);$d=$w.Documents.Open(" + quote(docx) + ",$false,$true);$text=$d.Content.Text;"
    script += "$out=@{experiment='native-word-report';prepared_execution=$true;word_version=$w.Version;word_build=$w.Build;pages=$d.ComputeStatistics(2);reopened=$true;checks=@{actual=$text.Contains('$686,500');budget=$text.Contains('$645,000');variance=$text.Contains('$41,500');cloud=$text.Contains('$28,000');synthetic=$text.Contains('fictional dataset')};native_seconds=$clock.Elapsed.TotalSeconds};$out|ConvertTo-Json -Depth 8;$d.Close(0);$w.Quit()"
    native = machine.exec(script, desktop=True, timeout_s=45)
    if native.exit_code != 0 or native.timed_out:
        raise RuntimeError('Word execution did not complete; inspect existing files and the application before retrying')
    result=json.loads(native.stdout)
    result.update(api_ms=native.ms,setup_api_ms=setup.ms,controller_seconds=time.perf_counter()-started,per_task_usd=None)
    result['result']='PASS' if all(result['checks'].values()) else 'FAIL'
    return result

if __name__ == '__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('machine');p.add_argument('--directory',required=True);p.add_argument('--report',type=Path,required=True);a=p.parse_args()
    result=run(Panes().machines.get(a.machine),a.directory);a.report.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
