import contextlib
import hashlib
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile

source = Path('/Users/niltonconstantino/personal/workspace.personal/intrepid/discussion-framework')
out = Path(tempfile.mkdtemp(prefix='wrk7-discussion-research-'))
snapshot = out / 'source-copy'
snapshot.mkdir()
tracked = subprocess.check_output(['git', '-C', str(source), 'ls-files'], text=True).splitlines()
selected = [p for p in tracked if p.startswith(('src/', 'tests/')) or p in ('README.md', 'pyproject.toml')]
def manifest():
    return {p: hashlib.sha256((source / p).read_bytes()).hexdigest() for p in selected}
before = manifest()
for relative in selected:
    target = snapshot / relative
    target.parent.mkdir(parents=True, exist_ok=True)
    shutil.copyfile(source / relative, target)
env = dict(os.environ, PYTHONPATH=str(snapshot / 'src'), PYTHONDONTWRITEBYTECODE='1')
tests = subprocess.run([sys.executable, '-B', '-m', 'unittest', 'discover', '-s', 'tests', '-v'], cwd=snapshot, env=env, capture_output=True, text=True, timeout=60)
(out / 'upstream-tests.log').write_text(tests.stdout + '\n' + tests.stderr)
sys.dont_write_bytecode = True
sys.path.insert(0, str(snapshot / 'src'))
from discussion_framework.cli import main
from discussion_framework.model import DiscussionIndex
from discussion_framework.validation import validate

fixture = out / 'fixture'
fixture.mkdir()
stages = []
def run(*args):
    output, error = io.StringIO(), io.StringIO()
    with contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
        code = main(['--root', str(fixture), *args])
    if code:
        raise RuntimeError((args, code, output.getvalue(), error.getvalue()))
def capture(label):
    index = DiscussionIndex.load(fixture)
    item = index.discussions[0]
    stages.append({'stage': label, 'discussion': item['status'], 'decisions': [{k: x.get(k) for k in ('id', 'status', 'ref_agenda')} for x in item['decisions']], 'plans': [{k: x.get(k) for k in ('id', 'status', 'ref_decisions')} for x in item['plans']], 'validationErrors': validate(fixture)})
    target = out / 'examples' / label
    target.mkdir(parents=True)
    shutil.copyfile(fixture / 'discussion/index.ndjson', target / 'index.ndjson')
    for path in (fixture / 'discussion/workflow/decisions').glob('*.md'):
        shutil.copyfile(path, target / path.name)
run('init')
run('start', 'importer-fixture', 'Importer fixture')
capture('agenda-open')
run('accept-agenda', 'DSC-0001')
run('add-decision', 'DSC-0001', '--title', 'Fixture decision')
capture('decision-open')
decision = fixture / 'discussion/workflow/decisions/DEC-0001-fixture-decision.md'
decision_text = decision.read_text()
decision.write_text(decision_text.replace('status: open', 'status: done'))
status_mismatch = validate(fixture)
decision.write_text(decision_text)
index = DiscussionIndex.load(fixture)
index.discussions[0]['decisions'][0]['ref_agenda'] = 'AGD-9999'
index.save()
broken_reference = validate(fixture)
index.discussions[0]['decisions'][0]['ref_agenda'] = 'AGD-0001'
index.save()
run('accept-decision', 'DSC-0001')
capture('decision-accepted')
run('add-plan', 'DSC-0001', '--title', 'Fixture plan')
capture('plan-open')
run('mark-plan', 'PLN-0001', 'in_progress')
capture('plan-in-progress')
run('mark-plan', 'PLN-0001', 'done')
capture('plan-done')
run('housekeep', 'DSC-0001', '--no-lesson')
capture('housekept')
results = {
    'source': str(source),
    'commit': subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip(),
    'trackedSourceSha256': before,
    'sourceFilesUnchanged': before == manifest(),
    'upstreamTestCommand': 'python3 -B -m unittest discover -s tests -v (temporary source copy)',
    'upstreamTestExit': tests.returncode,
    'stages': stages,
    'generatedOpenDecisionMarkdown': decision_text,
    'validationGaps': {'indexVsFrontMatterStatusMismatchErrors': status_mismatch, 'nonexistentRefAgendaErrors': broken_reference},
    'limitations': ['Synthetic fixtures; no live consumer project was imported.', 'No explicit multiproject/targets format was found in this checkout.', 'No importer implementation or migration was executed.'],
}
(out / 'inspection.json').write_text(json.dumps(results, ensure_ascii=False, indent=2) + '\n')
print(json.dumps({'directory': str(out), 'testsExit': tests.returncode, 'sourceFilesUnchanged': results['sourceFilesUnchanged'], 'stages': stages}, ensure_ascii=False, indent=2))
print(tests.stderr)
