import json
import os
import platform
from datetime import datetime, timezone
from pathlib import Path


class Collector:
    def __init__(self, config):
        self.config = config

    def collect(self):
        try:
            return {
                "package": {
                    "name": self.config.get_package_name(),
                    "version": self.config.get_package_version(),
                },
                "system": {
                    "platform": platform.system().lower(),
                    "arch": platform.machine(),
                    "pythonVersion": platform.python_version(),
                    "osType": platform.system(),
                    "osRelease": platform.release(),
                    "cpuCount": os.cpu_count(),
                },
                "installation": {
                    "timestamp": datetime.now(timezone.utc).isoformat(),
                    "cwd": str(Path.cwd()),
                    "isTopLevel": self.config.is_top_level_install(),
                    "pipReqTracker": os.getenv("PIP_REQ_TRACKER", "unknown"),
                    "pythonEnv": os.getenv("PYTHON_ENV", "unknown"),
                },
                "metadata": self.collect_metadata(),
            }
        except Exception:
            return {
                "package": {
                    "name": self.config.get_package_name(),
                    "version": self.config.get_package_version(),
                },
                "error": "Collection failed",
                "timestamp": datetime.now(timezone.utc).isoformat(),
            }

    def collect_metadata(self):
        metadata = {}
        git = self._read_gitconfig()

        if git.get("name"):
            metadata["gitUser"] = git["name"]
        if git.get("email"):
            email_parts = git["email"].split("@", 1)
            if len(email_parts) == 2:
                metadata["emailDomain"] = email_parts[1]

        ci = self._detect_ci()
        if ci:
            metadata["ci"] = ci

        pip_user = os.getenv("PIP_USER") or os.getenv("USER") or os.getenv("USERNAME")
        if pip_user:
            metadata["pipUser"] = pip_user

        return metadata

    def _read_gitconfig(self):
        path = Path.home() / ".gitconfig"
        if not path.exists():
            return {}

        result = {}
        in_user = False

        try:
            for raw_line in path.read_text(encoding="utf-8").splitlines():
                line = raw_line.strip()
                if line.lower() == "[user]":
                    in_user = True
                    continue
                if line.startswith("[") and line.endswith("]"):
                    in_user = False
                    continue

                if not in_user or "=" not in raw_line:
                    continue

                key, value = raw_line.split("=", 1)
                key = key.strip().lower()
                value = value.strip().strip("\"'")
                if key == "name" and "name" not in result:
                    result["name"] = value
                if key == "email" and "email" not in result:
                    result["email"] = value
        except Exception:
            return {}

        return result

    def _detect_ci(self):
        ci_keys = {
            "CI": os.getenv("CI"),
            "GITHUB_ACTIONS": "GitHub Actions" if os.getenv("GITHUB_ACTIONS") else None,
            "GITLAB_CI": "GitLab CI" if os.getenv("GITLAB_CI") else None,
            "JENKINS_URL": "Jenkins" if os.getenv("JENKINS_URL") else None,
            "TRAVIS": "Travis CI" if os.getenv("TRAVIS") else None,
            "CIRCLE_CI": "CircleCI" if os.getenv("CIRCLE_CI") else None,
            "BITBUCKET_BUILD_NUMBER": "Bitbucket Pipelines" if os.getenv("BITBUCKET_BUILD_NUMBER") else None,
        }

        detected = [{key: value} for key, value in ci_keys.items() if value is not None]
        return detected or None

    def format(self, data):
        return json.dumps(data)
