#!/usr/bin/env python3
"""Test real dependency-free demo files, without mocks of Charm's APIs.

For full checks use `go mod tidy`, `go test -race ./...`, and `go vet ./...`
in examples/worked. This script intentionally excludes Charm integration.
"""
from pathlib import Path
import json
import os
import subprocess
import sys

ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'examples/worked'
GROUPS={
    'internal/display': ['bounds.go','bounds_test.go'],
    'cmd/picker': ['selection.go','selection_test.go'],
    'cmd/search': ['request.go','request_test.go'],
    'cmd/tail': ['history.go','stream.go','history_test.go','stream_test.go'],
}

def main():
    env={**os.environ,'GO111MODULE':'off','GOTOOLCHAIN':'local'}
    total=0
    for directory,files in GROUPS.items():
        print(f'\n=== actual demo sources: {directory} ===',flush=True)
        result=subprocess.run(['go','test','-json','-race','-cover',*files],cwd=BASE/directory,
                              env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=90)
        for line in result.stdout.splitlines():
            try: event=json.loads(line)
            except json.JSONDecodeError: print(line);continue
            if event.get('Output'): print(event['Output'],end='')
            if event.get('Action')=='pass' and event.get('Test') and '/' not in event['Test']: total+=1
        if result.returncode: return result.returncode
        subprocess.run(['go','vet',*files],cwd=BASE/directory,env=env,check=True,timeout=60)
    print(f'\nPASS: {total} top-level demo-core tests; race checks and go vet for all four groups.')
    print('NOT RUN: Charm adapters, Charm-dependent rendering tests, or a real terminal.')
    return 0

if __name__=='__main__':
    sys.exit(main())
