#!/usr/bin/env python3
"""Controlled thread-cancellation fixture. Python 3.11+, standard library.

Writes only to a TemporaryDirectory beneath --scratch (default current directory).
No network, model calls or background workers left running after completion.
"""
import argparse
import asyncio
import concurrent.futures
import json
from pathlib import Path
import tempfile
import threading
import unittest

SCRATCH = Path.cwd()


async def scenario(mode="timeout", cooperative=False, committed_first=False):
    if mode not in ("timeout", "taskgroup"):
        raise ValueError("unknown mode")
    started = asyncio.Event()
    release = threading.Event()
    stop = threading.Event()
    loop = asyncio.get_running_loop()
    with tempfile.TemporaryDirectory(prefix="thread-fixture-", dir=SCRATCH) as tmp:
        destination = Path(tmp) / "effect.txt"
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        def worker():
            if committed_first:
                destination.write_text("committed", encoding="utf-8")
            loop.call_soon_threadsafe(started.set)
            if not release.wait(10):
                raise RuntimeError("fixture release watchdog expired")
            if cooperative and stop.is_set():
                return "stop_observed"
            destination.write_text("committed", encoding="utf-8")
            return "committed"

        # Retain the executor future independently of its cancellable async wrapper.
        underlying = executor.submit(worker)
        wrapped = asyncio.wrap_future(underlying)
        wrapper_state = "unexpected_completion"
        try:
            await asyncio.wait_for(started.wait(), timeout=5)
            if mode == "timeout":
                try:
                    await asyncio.wait_for(wrapped, timeout=0.01)
                    raise RuntimeError("worker unexpectedly completed before release")
                except TimeoutError:
                    wrapper_state = "timeout"
            else:
                async def await_worker():
                    return await wrapped

                async def fail():
                    raise ValueError("sibling failed")

                try:
                    async with asyncio.TaskGroup() as group:
                        group.create_task(await_worker())
                        group.create_task(fail())
                except* ValueError:
                    wrapper_state = "taskgroup_failed"
            observation = {
                "wrapper_state": wrapper_state,
                "async_wrapper_cancelled": wrapped.cancelled(),
                "thread_running_at_handler": underlying.running(),
                "thread_cancel_accepted": underlying.cancel(),
                "effect_at_handler": destination.exists(),
            }
            if cooperative:
                stop.set()
            release.set()
            # A fresh wrapper observes the retained running future after cancellation.
            observation["worker_result"] = await asyncio.wait_for(
                asyncio.wrap_future(underlying), timeout=5
            )
            observation["effect_after_join"] = destination.exists()
            return observation
        finally:
            release.set()
            # Cleanup may block briefly; this is a bounded test, not a service pattern.
            executor.shutdown(wait=True)


class ThreadTests(unittest.TestCase):
    def run_case(self, **kwargs):
        return asyncio.run(scenario(**kwargs))

    def test_timeout_leaves_running_thread(self):
        result = self.run_case()
        self.assertEqual(result["wrapper_state"], "timeout")
        self.assertTrue(result["thread_running_at_handler"])
        self.assertTrue(result["async_wrapper_cancelled"])

    def test_running_future_refuses_cancel(self):
        self.assertFalse(self.run_case()["thread_cancel_accepted"])

    def test_effect_happens_after_timeout_handler(self):
        result = self.run_case()
        self.assertFalse(result["effect_at_handler"])
        self.assertTrue(result["effect_after_join"])
        self.assertEqual(result["worker_result"], "committed")

    def test_taskgroup_does_not_stop_thread(self):
        result = self.run_case(mode="taskgroup")
        self.assertEqual(result["wrapper_state"], "taskgroup_failed")
        self.assertTrue(result["async_wrapper_cancelled"])
        self.assertTrue(result["thread_running_at_handler"])
        self.assertTrue(result["effect_after_join"])

    def test_cooperative_stop_before_checkpoint(self):
        result = self.run_case(cooperative=True)
        self.assertEqual(result["worker_result"], "stop_observed")
        self.assertFalse(result["effect_after_join"])

    def test_cooperative_stop_cannot_undo_committed_effect(self):
        result = self.run_case(cooperative=True, committed_first=True)
        self.assertTrue(result["effect_at_handler"])
        self.assertEqual(result["worker_result"], "stop_observed")
        self.assertTrue(result["effect_after_join"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--test", action="store_true")
    parser.add_argument("--scratch", type=Path, default=Path.cwd())
    args = parser.parse_args()
    SCRATCH = args.scratch.resolve(strict=True)
    if not SCRATCH.is_dir():
        parser.error("--scratch must be an existing directory")
    if args.test:
        unittest.main(argv=[__file__], verbosity=2)
    else:
        print(json.dumps({
            "timeout": asyncio.run(scenario()),
            "taskgroup": asyncio.run(scenario(mode="taskgroup")),
            "cooperative": asyncio.run(scenario(cooperative=True)),
            "already_committed": asyncio.run(scenario(cooperative=True, committed_first=True)),
        }, indent=2))
