#!/usr/bin/env python3
"""
CONSTITUTION_HASH Auto-Sync Tool

Computes current CONSTITUTION.md hash and updates .env CONSTITUTION_HASH line.
Prevents manual hash sync errors that brick the orchestrator.

Usage:
    python pulse/admin/update_constitution_hash.py

Exit Codes:
    0 = Hash updated or already synced
    1 = Error (missing files, no hash in .env)
"""

import hashlib
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent.parent.parent
CONST = ROOT / "Corpus_Callosum" / "CONSTITUTION.md"
ENV = ROOT / ".env"


def main():
    if not CONST.exists():
        print(f"ERROR: CONSTITUTION.md not found at {CONST}")
        return 1
    if not ENV.exists():
        print(f"ERROR: .env not found at {ENV}")
        return 1

    # Compute current hash
    new_hash = hashlib.sha256(CONST.read_bytes()).hexdigest()

    # Read .env
    lines = ENV.read_text(encoding="utf-8").splitlines()
    old_hash = None
    updated = False

    for i, line in enumerate(lines):
        if line.strip().startswith("CONSTITUTION_HASH="):
            old_hash = line.split("=", 1)[1].strip().strip("'\"")
            if old_hash != new_hash:
                lines[i] = f"CONSTITUTION_HASH={new_hash}"
                updated = True
            break

    if not old_hash:
        print("ERROR: CONSTITUTION_HASH not found in .env")
        return 1

    if not updated:
        print(f"[OK] CONSTITUTION_HASH already up to date: {new_hash}")
        return 0

    # Write updated .env
    ENV.write_text("\n".join(lines) + "\n", encoding="utf-8")

    print("CONSTITUTION_HASH updated:")
    print(f"  OLD: {old_hash}")
    print(f"  NEW: {new_hash}")
    print()
    print("Next step: Re-seal .env with:")
    print("  python pulse/admin/seal_env.py [private_key_path]")

    return 0


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