"""YC batch security audit - produces a per-company security header and TLS dataset.

Fetches all companies in a given YC batch (default W25) from YC's public API,
then runs passive security checks against each company's website:
  - Missing security headers (HSTS, CSP, X-Frame-Options, etc.)
  - Outdated TLS versions (TLS 1.0 / 1.1 accepted)
  - Exposed sensitive files (.env, .git/config, wp-config.php.bak, etc.)

Output: CSV with anonymized data suitable for press pitch + a per-company
detail file for internal reference.

Usage:
    python yc_security_audit.py --batch W25 --out scripts/yc-audit-out/
"""

from __future__ import annotations

import argparse  # CLI args
import csv  # CSV writer
import json  # per-company detail file
import os  # paths
import random  # sample subset if --limit
import socket  # raw TLS connect
import ssl  # TLS version probing
import sys  # stderr
import time  # pacing between scans
from dataclasses import asdict, dataclass, field  # structured results
from typing import Iterable  # typing
from urllib.parse import urlparse  # URL parsing

import httpx  # HTTP client (already a project dep)


YC_API_URL = "https://api.ycombinator.com/v0.1/companies/"
USER_AGENT = "ismycodesafe-audit/1.0 (+https://ismycodesafe.com)"

# Headers whose absence is a finding. Names are lowercased for lookup.
REQUIRED_HEADERS = {
    "strict-transport-security": "HSTS",
    "content-security-policy": "CSP",
    "x-frame-options": "X-Frame-Options",
    "x-content-type-options": "X-Content-Type-Options",
    "referrer-policy": "Referrer-Policy",
    "permissions-policy": "Permissions-Policy",
}

# Paths we probe for accidental exposure. Keep the list short to stay polite.
SENSITIVE_PATHS = (
    ".env",
    ".git/config",
    ".git/HEAD",
    "wp-config.php.bak",
    "backup.sql",
    ".DS_Store",
    "phpinfo.php",
)


@dataclass
class AuditResult:
    """Per-company result - all the data we need for aggregation + pitch."""

    name: str
    website: str
    hostname: str
    reachable: bool = False
    status_code: int | None = None
    missing_headers: list[str] = field(default_factory=list)
    tls_versions: list[str] = field(default_factory=list)
    weak_tls_accepted: bool = False
    exposed_paths: list[str] = field(default_factory=list)
    error: str | None = None


def fetch_yc_batch(batch: str) -> list[dict]:
    """Page through YC's public API and return every company in ``batch``."""
    companies: list[dict] = []
    page = 1
    with httpx.Client(timeout=15.0) as client:
        while True:
            response = client.get(
                YC_API_URL,
                params={"batch": batch, "page": page},
                headers={"User-Agent": USER_AGENT},
            )
            response.raise_for_status()
            data = response.json()
            batch_companies = data.get("companies", [])
            if not batch_companies:
                break
            # Tag each company with the batch we found them in for later grouping
            for company in batch_companies:
                company.setdefault("batch", batch)
            companies.extend(batch_companies)
            total_pages = data.get("totalPages", 1)
            if page >= total_pages:
                break
            page += 1
    return companies


def fetch_yc_batches(batches: list[str]) -> list[dict]:
    """Fetch multiple batches and concatenate, deduplicating on company id."""
    all_companies: list[dict] = []
    seen_ids: set[int] = set()
    for batch in batches:
        for company in fetch_yc_batch(batch):
            cid = company.get("id")
            if cid in seen_ids:
                continue
            if cid is not None:
                seen_ids.add(cid)
            all_companies.append(company)
    return all_companies


def check_headers(url: str) -> tuple[bool, int | None, list[str], str | None]:
    """HEAD/GET the homepage and return (reachable, status, missing_headers, error)."""
    try:
        with httpx.Client(
            timeout=12.0,
            follow_redirects=True,
            headers={"User-Agent": USER_AGENT},
        ) as client:
            response = client.get(url)
    except httpx.HTTPError as exc:
        return False, None, [], str(exc)

    present = {h.lower() for h in response.headers}
    missing = [
        label for header, label in REQUIRED_HEADERS.items() if header not in present
    ]
    return True, response.status_code, missing, None


def check_tls(hostname: str) -> tuple[list[str], bool]:
    """Probe TLS 1.0 / 1.1 / 1.2 / 1.3 support; return (versions, weak_accepted)."""
    probe_versions = [
        ("TLSv1.0", ssl.TLSVersion.TLSv1),
        ("TLSv1.1", ssl.TLSVersion.TLSv1_1),
        ("TLSv1.2", ssl.TLSVersion.TLSv1_2),
        ("TLSv1.3", ssl.TLSVersion.TLSv1_3),
    ]
    accepted: list[str] = []
    for label, version in probe_versions:
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        try:
            context.minimum_version = version
            context.maximum_version = version
        except (ValueError, AttributeError):
            continue  # this Python build does not support that version
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        if version in (ssl.TLSVersion.TLSv1, ssl.TLSVersion.TLSv1_1):
            # OpenSSL 3 refuses TLS 1.0/1.1 client-side below SECLEVEL 0; without this the probe always reports "rejected".
            context.set_ciphers("DEFAULT:@SECLEVEL=0")
        try:
            with socket.create_connection((hostname, 443), timeout=5) as sock:
                with context.wrap_socket(sock, server_hostname=hostname):
                    accepted.append(label)
        except (OSError, ssl.SSLError):
            pass  # that version rejected - good (for modern) or silent (for old)
    weak = any(v in accepted for v in ("TLSv1.0", "TLSv1.1"))
    return accepted, weak


def check_exposed_paths(url: str) -> list[str]:
    """Try each sensitive path; return list of 200-reachable paths."""
    exposed: list[str] = []
    base = url.rstrip("/")
    with httpx.Client(
        timeout=8.0,
        follow_redirects=False,
        headers={"User-Agent": USER_AGENT},
    ) as client:
        for path in SENSITIVE_PATHS:
            try:
                response = client.get(f"{base}/{path}")
            except httpx.HTTPError:
                continue
            # 200 with non-trivial body is the signal. Some sites 200-to-HTML
            # on 404 (SPA catch-all) - filter those by content signature.
            if response.status_code == 200 and _looks_like_real_content(response, path):
                exposed.append(path)
    return exposed


def _looks_like_real_content(response: httpx.Response, path: str) -> bool:
    """Heuristic: the response body must match the path type, not an SPA 404."""
    body = response.text[:1000]
    content_type = response.headers.get("content-type", "").lower()
    if "text/html" in content_type:
        return False  # SPA catch-all serving index.html - not a real leak
    if path == ".env":
        return "=" in body and ("\n" in body or body.startswith(("APP_", "DB_", "API_")))
    if path.startswith(".git"):
        return body.startswith(("ref:", "[core]", "[", "gitdir:"))
    if path == "wp-config.php.bak":
        return "DB_NAME" in body or "DB_PASSWORD" in body
    if path == "backup.sql":
        return body.startswith(("--", "/*", "INSERT ", "CREATE "))
    if path == ".DS_Store":
        return response.content[:4] == b"\x00\x00\x00\x01"  # macOS DS_Store magic
    return len(body) > 0  # fall-through: non-empty non-HTML


def audit_one(name: str, website: str) -> AuditResult:
    """Run all checks against a single company; always returns a result."""
    parsed = urlparse(website)
    hostname = parsed.hostname or ""
    result = AuditResult(name=name, website=website, hostname=hostname)

    if not hostname:
        result.error = "Invalid URL"
        return result

    reachable, status, missing, error = check_headers(website)
    result.reachable = reachable
    result.status_code = status
    result.missing_headers = missing
    if error:
        result.error = error
        return result

    try:
        tls_versions, weak = check_tls(hostname)
        result.tls_versions = tls_versions
        result.weak_tls_accepted = weak
    except Exception as exc:  # noqa: BLE001 - TLS probe failures must not abort audit
        result.error = f"TLS probe failed: {exc}"

    try:
        result.exposed_paths = check_exposed_paths(website)
    except Exception as exc:  # noqa: BLE001 - path probe failures must not abort audit
        if not result.error:
            result.error = f"Path probe failed: {exc}"

    return result


def run_audit(
    companies: Iterable[dict],
    *,
    limit: int | None,
    pacing_seconds: float,
    progress_stream=sys.stderr,
) -> list[AuditResult]:
    """Iterate companies, audit each, return results."""
    selected = list(companies)
    if limit and limit < len(selected):
        selected = random.sample(selected, limit)

    results: list[AuditResult] = []
    total = len(selected)
    for index, company in enumerate(selected, start=1):
        name = company.get("name", "?")
        website = company.get("website", "") or ""
        if not website:
            print(f"  [{index}/{total}] SKIP {name} - no website", file=progress_stream)
            continue
        print(f"  [{index}/{total}] scanning {name} ({website})", file=progress_stream)
        try:
            result = audit_one(name, website)
        except Exception as exc:  # noqa: BLE001 - single-company failure must not kill batch
            result = AuditResult(name=name, website=website, hostname="", error=str(exc))
        results.append(result)
        if index < total:
            time.sleep(pacing_seconds)
    return results


def write_outputs(results: list[AuditResult], out_dir: str, batch: str) -> dict[str, str]:
    """Write anonymized CSV + detailed JSON, return paths."""
    os.makedirs(out_dir, exist_ok=True)

    anon_csv = os.path.join(out_dir, f"yc-{batch.lower()}-audit-anon.csv")
    detail_json = os.path.join(out_dir, f"yc-{batch.lower()}-audit-detail.json")
    summary_md = os.path.join(out_dir, f"yc-{batch.lower()}-summary.md")

    # Anonymized CSV - no company name, only findings
    with open(anon_csv, "w", encoding="utf-8", newline="") as fh:
        writer = csv.writer(fh)
        writer.writerow([
            "anon_id",
            "reachable",
            "status_code",
            "missing_header_count",
            "missing_headers",
            "weak_tls_accepted",
            "tls_versions",
            "exposed_path_count",
            "exposed_paths",
        ])
        for idx, r in enumerate(results, start=1):
            writer.writerow([
                f"company-{idx:03d}",
                int(r.reachable),
                r.status_code or "",
                len(r.missing_headers),
                "|".join(r.missing_headers),
                int(r.weak_tls_accepted),
                "|".join(r.tls_versions),
                len(r.exposed_paths),
                "|".join(r.exposed_paths),
            ])

    # Full JSON - for your eyes only, not for the pitch
    with open(detail_json, "w", encoding="utf-8") as fh:
        json.dump([asdict(r) for r in results], fh, indent=2, ensure_ascii=False)

    # Human-readable summary for the pitch
    reachable = [r for r in results if r.reachable]
    missing_2plus = [r for r in reachable if len(r.missing_headers) >= 2]
    weak_tls = [r for r in reachable if r.weak_tls_accepted]
    exposed = [r for r in reachable if r.exposed_paths]

    total = len(reachable)
    with open(summary_md, "w", encoding="utf-8") as fh:
        fh.write(f"# YC {batch} Security Audit - Summary\n\n")
        fh.write(f"Audited **{len(results)}** companies from YC {batch}. "
                 f"**{total}** reachable and scannable.\n\n")
        fh.write("## Findings\n\n")
        if total:
            fh.write(f"- **{len(missing_2plus)}/{total}** "
                     f"({len(missing_2plus)*100//total}%) missing 2+ critical security headers\n")
            fh.write(f"- **{len(weak_tls)}/{total}** "
                     f"({len(weak_tls)*100//total}%) accept TLS 1.0 or TLS 1.1 "
                     "(deprecated since 2020)\n")
            fh.write(f"- **{len(exposed)}/{total}** "
                     f"({len(exposed)*100//total}%) exposing sensitive files "
                     "(.env, .git, backups)\n")
        fh.write("\n## Methodology\n\n")
        fh.write("- All checks are passive (no exploitation, no brute-force).\n")
        fh.write(f"- Headers probed via single HTTPS GET as `{USER_AGENT}`.\n")
        fh.write("- TLS version support probed with Python ssl module (minimum=maximum).\n")
        fh.write("- Sensitive paths probed with single GET; content validated "
                 "against path-specific signature to reject SPA catch-all 404s.\n")

    return {"csv": anon_csv, "json": detail_json, "summary": summary_md}


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--batch", default="W25",
                        help="YC batch code(s). Comma-separated for multiple "
                             "(e.g. W25,S24,W24)")
    parser.add_argument("--limit", type=int, default=None,
                        help="Random sample of N companies (default: all)")
    parser.add_argument("--out", default="scripts/yc-audit-out",
                        help="Output directory (created if missing)")
    parser.add_argument("--pacing", type=float, default=1.0,
                        help="Seconds between company scans (default: 1.0)")
    args = parser.parse_args()

    batches = [b.strip() for b in args.batch.split(",") if b.strip()]
    print(f"Fetching YC {', '.join(batches)} companies...", file=sys.stderr)
    companies = fetch_yc_batches(batches)
    print(f"Found {len(companies)} companies across {len(batches)} batch(es)", file=sys.stderr)
    if not companies:
        print(f"No companies found - check batch codes '{args.batch}'", file=sys.stderr)
        return 1

    print(f"Running audit (limit={args.limit}, pacing={args.pacing}s)...", file=sys.stderr)
    results = run_audit(
        companies,
        limit=args.limit,
        pacing_seconds=args.pacing,
    )

    # Use combined batch label for output filenames (e.g. "w25-s24")
    batch_label = "-".join(b.lower() for b in batches)
    outputs = write_outputs(results, args.out, batch_label)
    print("\nDone. Outputs:", file=sys.stderr)
    for label, path in outputs.items():
        print(f"  {label}: {path}", file=sys.stderr)
    return 0


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