import json
from datetime import datetime
from pathlib import Path

from core.models import DiscoveryResult
from output.base import AbstractOutput


class JsonOutput(AbstractOutput):
    """Writes all discovery results to a JSON file on finalize."""

    def __init__(self, path: Path) -> None:
        self._path = path

    def emit(self, result: DiscoveryResult) -> None:
        pass  # collected via finalize

    def finalize(self, results: list[DiscoveryResult]) -> None:
        succeeded = [r for r in results if r.succeeded]
        data = {
            "timestamp": datetime.now().isoformat(),
            "summary": {
                "total": len(results),
                "succeeded": len(succeeded),
                "blocked": len(results) - len(succeeded),
                "success_rate": len(succeeded) / len(results) if results else 0.0,
            },
            "effective_probes": [r.model_dump() for r in succeeded],
            "all_results": [r.model_dump() for r in results],
        }
        self._path.write_text(json.dumps(data, indent=2, ensure_ascii=False))
