"""
LaunchReadinessReceipt: Proof that system components are ready for release.

This receipt captures the results of running a verification suite against
all system components. It provides cryptographic evidence that:
- CLI commands work
- Tests pass
- Artifacts can be generated
- The system is internally consistent

Used as a gate for releases, demos, and CI pipelines.

Schema: launch_readiness.v1
"""
from __future__ import annotations

import platform
import subprocess
from datetime import datetime, timezone
from typing import List, Literal, Optional

from assay._receipts.compat.pyd import Field
from assay._receipts.base import BaseReceipt, Domain


class CheckResult(BaseReceipt):
    """Result of a single verification check."""

    receipt_type: str = Field(default="CheckResult")
    domain: str = Field(default=Domain.GOVERNANCE.value)

    # Check identification
    name: str = Field(description="Name of the check (e.g., 'assay_demo')")
    cmd: List[str] = Field(description="Exact command that was run")
    cwd: str = Field(description="Working directory for the command")

    # Results
    passed: bool = Field(description="Whether the check passed")
    exit_code: int = Field(description="Exit code of the command")
    duration_ms: int = Field(ge=0, description="Duration in milliseconds")

    # Artifacts
    stdout_path: Optional[str] = Field(default=None, description="Path to stdout capture file")
    stderr_path: Optional[str] = Field(default=None, description="Path to stderr capture file")
    artifact_hash: Optional[str] = Field(
        default=None,
        description="SHA256 hash of {cmd, cwd, exit_code, stdout_bytes, stderr_bytes}"
    )

    # Error details
    error_message: Optional[str] = Field(
        default=None,
        description="Error message if check failed"
    )


class SystemFingerprint(BaseReceipt):
    """Machine fingerprint for reproducibility."""

    receipt_type: str = Field(default="SystemFingerprint")
    domain: str = Field(default=Domain.GOVERNANCE.value)

    platform: str = Field(description="Platform identifier (e.g., 'Darwin-23.0.0-arm64')")
    python_version: str = Field(description="Python version")
    git_commit: Optional[str] = Field(default=None, description="Git commit hash")
    git_dirty: bool = Field(default=False, description="Whether working tree has uncommitted changes")


class ComponentSummary(BaseReceipt):
    """Summary of check results."""

    receipt_type: str = Field(default="ComponentSummary")
    domain: str = Field(default=Domain.GOVERNANCE.value)

    total: int = Field(ge=0, description="Total number of checks")
    passed: int = Field(ge=0, description="Number of checks that passed")
    failed: int = Field(ge=0, description="Number of checks that failed")
    skipped: int = Field(default=0, ge=0, description="Number of checks skipped")


class LaunchReadinessReceipt(BaseReceipt):
    """
    Proof that system is ready for release.

    This receipt is generated by `assay launch-check` and captures
    the results of running a comprehensive verification suite.

    Every claim of "shippable" must be backed by this receipt.
    """

    receipt_type: str = Field(default="LaunchReadinessReceipt")
    domain: str = Field(default=Domain.GOVERNANCE.value)

    # Metadata
    generated_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc),
        description="When this receipt was generated"
    )

    # System fingerprint
    system_fingerprint: SystemFingerprint = Field(
        description="Machine fingerprint for reproducibility"
    )

    # Check results
    checks: List[CheckResult] = Field(
        default_factory=list,
        description="Results of each verification check"
    )

    # Summary
    component_summary: ComponentSummary = Field(
        description="Summary of pass/fail counts"
    )

    # Overall result
    overall_passed: bool = Field(
        description="True if all required checks passed"
    )

    # Artifacts location
    artifacts_dir: Optional[str] = Field(
        default=None,
        description="Directory where stdout/stderr captures are stored"
    )


def get_system_fingerprint() -> SystemFingerprint:
    """Collect current system fingerprint."""
    import uuid

    git_commit = None
    git_dirty = False

    try:
        result = subprocess.run(
            ["git", "rev-parse", "--short", "HEAD"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            git_commit = result.stdout.strip()

        result = subprocess.run(
            ["git", "status", "--porcelain"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            git_dirty = bool(result.stdout.strip())
    except Exception:
        pass

    return SystemFingerprint(
        receipt_id=f"fp_{uuid.uuid4().hex[:16]}",
        platform=platform.platform(),
        python_version=platform.python_version(),
        git_commit=git_commit,
        git_dirty=git_dirty,
    )


def create_launch_readiness_receipt(
    checks: List[CheckResult],
    artifacts_dir: Optional[str] = None,
) -> LaunchReadinessReceipt:
    """Factory for creating LaunchReadinessReceipt."""
    import uuid

    passed_count = sum(1 for c in checks if c.passed)
    failed_count = sum(1 for c in checks if not c.passed)

    summary = ComponentSummary(
        receipt_id=f"sum_{uuid.uuid4().hex[:16]}",
        total=len(checks),
        passed=passed_count,
        failed=failed_count,
    )

    return LaunchReadinessReceipt(
        receipt_id=f"launch_{uuid.uuid4().hex[:16]}",
        system_fingerprint=get_system_fingerprint(),
        checks=checks,
        component_summary=summary,
        overall_passed=(failed_count == 0),
        artifacts_dir=artifacts_dir,
    )


__all__ = [
    "CheckResult",
    "SystemFingerprint",
    "ComponentSummary",
    "LaunchReadinessReceipt",
    "get_system_fingerprint",
    "create_launch_readiness_receipt",
]
