"""CLI entry points."""

from __future__ import annotations

import argparse
import shutil
import sys
from pathlib import Path


def keygen() -> None:
    """Generate a new P2P identity keypair."""
    p = argparse.ArgumentParser(description="Generate P2P identity")
    p.add_argument("-d", "--dir", default="~/.p2p/identity")
    p.add_argument("-p", "--passphrase", default="")
    p.add_argument("-f", "--force", action="store_true")
    a = p.parse_args()

    from p2p.identity import PeerIdentity

    d = Path(a.dir).expanduser()
    if (d / "private.pem").exists() and not a.force:
        identity = PeerIdentity.load(d, a.passphrase)
        print(f"Exists: {identity.peer_id}")
        print(f"Use --force to regenerate")
        sys.exit(0)

    identity = PeerIdentity.generate()
    identity.save(d, a.passphrase)
    print(f"PeerID: {identity.peer_id}")
    print(f"Keys:   {d}/")


def reset() -> None:
    """Reset P2P state: regenerate identity and clear all peer connections.

    Use after protocol-breaking upgrades. All peers will need to
    re-handshake with the new identity.
    """
    p = argparse.ArgumentParser(description="Reset P2P identity and connections")
    p.add_argument("-d", "--dir", default="~/.p2p")
    p.add_argument("-p", "--passphrase", default="")
    p.add_argument("--keep-peers", action="store_true",
                   help="Keep peer store but reset trust (require re-handshake)")
    p.add_argument("-y", "--yes", action="store_true",
                   help="Skip confirmation")
    a = p.parse_args()

    base = Path(a.dir).expanduser()
    identity_dir = base / "identity"
    peers_path = base / "peers.json"

    if not a.yes:
        print(f"This will:")
        print(f"  1. Generate a new identity keypair (new PeerID)")
        if a.keep_peers:
            print(f"  2. Reset all peer trust levels to 0 (require re-handshake)")
        else:
            print(f"  2. Delete all peer records")
        print(f"\nAll existing connections will break. Peers must re-handshake.")
        resp = input("Continue? [y/N] ")
        if resp.lower() != "y":
            print("Aborted.")
            sys.exit(0)

    # Regenerate identity
    from p2p.identity import PeerIdentity

    if identity_dir.exists():
        shutil.rmtree(identity_dir)
    identity = PeerIdentity.generate()
    identity.save(identity_dir, a.passphrase)
    print(f"New PeerID: {identity.peer_id}")

    # Handle peer store
    if peers_path.exists():
        if a.keep_peers:
            import json
            data = json.loads(peers_path.read_text())
            for pid, rec in data.items():
                rec["trust_level"] = 0
                rec["public_key_pem"] = ""
                rec["last_seen"] = 0.0
            peers_path.write_text(json.dumps(data, indent=2))
            print(f"Reset trust for {len(data)} peers (kept records)")
        else:
            peers_path.unlink()
            print("Deleted peer store")

    print("\nDone. Share your new PeerID with peers and restart your agent.")
    from p2p import PROTOCOL_VERSION
    print(f"Protocol version: {PROTOCOL_VERSION}")
