import argparse
import sys
from .installer import install, install_many


def main():
    parser = argparse.ArgumentParser(
        prog="peep",
        description="A smarter pip — handles version conflicts, build errors, and platform issues automatically.",
    )

    subparsers = parser.add_subparsers(dest="command", required=True)

    # ── peep install ──────────────────────────────────────────────────────────
    install_parser = subparsers.add_parser("install", help="Install one or more packages")
    install_parser.add_argument("packages", nargs="+", help="Package(s) to install, e.g. requests or requests==2.28.0")
    install_parser.add_argument("-v", "--verbose", action="store_true", help="Show detailed output")
    install_parser.add_argument("--force", action="store_true", help="Force reinstall even if already installed")

    # ── peep check ───────────────────────────────────────────────────────────
    check_parser = subparsers.add_parser("check", help="Check a package for compatibility without installing")
    check_parser.add_argument("package", help="Package to check")
    check_parser.add_argument("-v", "--verbose", action="store_true")

    args = parser.parse_args()

    if args.command == "install":
        _handle_install(args)
    elif args.command == "check":
        _handle_check(args)


def _handle_install(args):
    # Parse packages — support both `requests` and `requests==2.28.0`
    parsed = [_parse_package_arg(p) for p in args.packages]

    if len(parsed) == 1:
        name, version = parsed[0]
        _print_status(f"Installing {name}" + (f"=={version}" if version else "") + "...")
        report = install(name, version=version, verbose=args.verbose)
        _print_report(report)
    else:
        _print_status(f"Installing {len(parsed)} packages...")
        reports = install_many([p for p, _ in parsed], verbose=args.verbose)
        for report in reports:
            _print_report(report)

    # Exit with error code if any install failed
    if isinstance(reports if len(parsed) > 1 else [report], list):
        results = reports if len(parsed) > 1 else [report]
        if any(not r["success"] for r in results):
            sys.exit(1)


def _handle_check(args):
    from .environment import check_python_compatibility, check_platform_compatibility
    from .resolver import resolve_conflicts

    name, version = _parse_package_arg(args.package)
    _print_status(f"Checking {name}" + (f"=={version}" if version else "") + "...")

    py = check_python_compatibility(name, version)
    plat = check_platform_compatibility(name, version)
    deps = resolve_conflicts(name, version)

    print()
    _section("Python compatibility")
    if py.get("compatible") is True:
        _ok(f"Compatible with Python {py.get('current_python')}")
    elif py.get("compatible") is False:
        _warn(f"Requires Python {py.get('requires_python')}, you have {py.get('current_python')}")
        if py.get("suggested_version"):
            _info(f"Suggested version: {name}=={py['suggested_version']}")
    else:
        _info("Could not determine Python compatibility")

    _section("Platform compatibility")
    if plat.get("has_compatible_wheel"):
        _ok("Compatible wheel available for your platform")
    elif plat.get("needs_compilation"):
        _warn("No wheel available — package will be compiled from source")
    elif not plat.get("has_sdist"):
        _err("No compatible distribution found for your platform")

    _section("Dependency conflicts")
    if deps["clean"]:
        _ok("No conflicts detected")
    else:
        for conflict in deps["conflicts"]:
            _err(f"{conflict['package']} {conflict['installed']} installed, but {conflict['required']} required by {conflict['required_by']}")
        for upgrade in deps["to_upgrade"]:
            _warn(f"{upgrade['package']} will be upgraded {upgrade['from']} → {upgrade['to']}")


def _print_report(report: dict):
    pkg = report["package"]
    ver = report.get("final_version")

    print()
    if report["success"]:
        label = f"{pkg}=={ver}" if ver else pkg
        _ok(f"Successfully installed {label}")
    else:
        _err(f"Failed to install {pkg}: {report.get('error', 'Unknown error')}")


def _parse_package_arg(pkg_str: str) -> tuple[str, str | None]:
    """Parse 'requests==2.28.0' into ('requests', '2.28.0'), or 'requests' into ('requests', None)."""
    if "==" in pkg_str:
        name, version = pkg_str.split("==", 1)
        return name.strip(), version.strip()
    return pkg_str.strip(), None


# ── Terminal output helpers ────────────────────────────────────────────────────

RESET  = "\033[0m"
GREEN  = "\033[32m"
YELLOW = "\033[33m"
RED    = "\033[31m"
CYAN   = "\033[36m"
BOLD   = "\033[1m"

def _print_status(msg): print(f"{BOLD}{CYAN}→ {msg}{RESET}")
def _section(label):    print(f"\n{BOLD}{label}{RESET}")
def _ok(msg):           print(f"  {GREEN}✔ {msg}{RESET}")
def _warn(msg):         print(f"  {YELLOW}⚠ {msg}{RESET}")
def _err(msg):          print(f"  {RED}✘ {msg}{RESET}")
def _info(msg):         print(f"  {CYAN}ℹ {msg}{RESET}")