import json
from hivebee import load_config

def generate_honeyfiles(profile):
    """
    Send system profile to Claude API.
    Returns list of honeyfile dicts with filename, path, content.
    """
    try:
        import anthropic
    except ImportError:
        print("[hivebee] anthropic package not found")
        return fallback_honeyfiles(profile)

    config = load_config()
    api_key = config.get('ai', {}).get('api_key', '')

    if not api_key:
        print("[hivebee] No API key set — using fallback honeyfiles")
        return fallback_honeyfiles(profile)

    prompt = f"""You are a cybersecurity expert generating convincing fake files (honeyfiles) for an intrusion detection system.

System profile:
{json.dumps(profile, indent=2)}

Generate exactly 4 honeyfiles for this system. Each file must:
- Have a filename that looks real and tempting to an attacker
- Contain realistic-looking fake sensitive data
- Be placed in a logical path for this system type
- Look like it genuinely belongs on this machine

Return ONLY a JSON array, no other text, no markdown:
[
  {{
    "filename": "example.txt",
    "path": "/home/user/",
    "content": "fake content here"
  }}
]"""

    try:
        client = anthropic.Anthropic(api_key=api_key)
        response = client.messages.create(
            model=config.get('ai', {}).get('model', 'claude-sonnet-4-20250514'),
            max_tokens=1000,
            messages=[{"role": "user", "content": prompt}]
        )
        raw = response.content[0].text.strip()
        raw = raw.replace('```json', '').replace('```', '').strip()
        return json.loads(raw)
    except Exception as e:
        print(f"[hivebee] AI generation failed: {e}")
        return fallback_honeyfiles(profile)

def fallback_honeyfiles(profile):
    """
    Static fallback honeyfiles based on system type.
    Used when no API key is set.
    """
    system_type = profile.get('system_type', 'general')

    templates = {
        'web_server': [
            {
                "filename": ".env.backup",
                "path": "/var/www/html/",
                "content": "DB_HOST=localhost\nDB_USER=admin\nDB_PASS=Sup3rS3cr3t!\nDB_NAME=production\nAPI_KEY=sk-prod-abc123xyz789\nSECRET_KEY=do-not-share-2024"
            },
            {
                "filename": "db_credentials.txt",
                "path": "/root/",
                "content": "MySQL Root: root / R00tP@ssw0rd!\nMySQL App:  webapp / W3bApp#2024\nHost: localhost:3306"
            },
            {
                "filename": "wp-config-backup.php",
                "path": "/var/www/html/",
                "content": "<?php\ndefine('DB_NAME', 'wordpress_prod');\ndefine('DB_USER', 'wp_admin');\ndefine('DB_PASSWORD', 'WpS3cur3#2024');\ndefine('DB_HOST', 'localhost');\n?>"
            },
            {
                "filename": "ssh_keys_backup.txt",
                "path": "/root/",
                "content": "Server: prod-web-01\nSSH User: deploy\nSSH Pass: D3pl0y@2024\nKey: /root/.ssh/id_rsa"
            },
        ],
        'database_server': [
            {
                "filename": "mysql_root_credentials.txt",
                "path": "/root/",
                "content": "MySQL Root Password: DbR00t#Secure2024\nHost: localhost\nPort: 3306\nAdmin Panel: http://localhost/phpmyadmin"
            },
            {
                "filename": "database_backup_config.txt",
                "path": "/root/",
                "content": "Backup Server: 192.168.1.50\nBackup User: backup_admin\nBackup Pass: B4ckup!Secure\nSchedule: daily 02:00"
            },
            {
                "filename": "replication_credentials.txt",
                "path": "/etc/mysql/",
                "content": "Master: 192.168.1.10\nSlave:  192.168.1.11\nUser: replication\nPass: Repl!c4tion2024"
            },
            {
                "filename": "db_users_export.csv",
                "path": "/root/",
                "content": "username,password_hash,role\nadmin,$2b$12$xyz123,superadmin\napp_user,$2b$12$abc456,readwrite\nreport,$2b$12$def789,readonly"
            },
        ],
        'office_finance': [
            {
                "filename": "salary_2024.xlsx",
                "path": f"/home/{profile.get('users', ['user'])[0]}/Documents/",
                "content": "Employee,Department,Salary\nJohn Smith,Engineering,145000\nSarah Jones,Finance,98000\nMike Brown,Operations,87000"
            },
            {
                "filename": "bank_account_details.txt",
                "path": f"/home/{profile.get('users', ['user'])[0]}/Documents/",
                "content": "Account: 4821-XXXX-XXXX-9032\nRouting: 021000021\nBalance: $482,291.44\nBank: First National Business"
            },
            {
                "filename": "tax_returns_2024.txt",
                "path": f"/home/{profile.get('users', ['user'])[0]}/Documents/",
                "content": "Company: Acme Corp Ltd\nEIN: 82-XXXXXXX\nGross Revenue: $4,200,000\nNet Income: $890,000"
            },
            {
                "filename": "passwords_personal.txt",
                "path": f"/home/{profile.get('users', ['user'])[0]}/",
                "content": "Email: P@ssw0rd#2024\nBanking: S3cur3Bank!\nVPN: Vpn@Acme2024"
            },
        ],
        'devops': [
            {
                "filename": "aws_credentials",
                "path": "/root/.aws/",
                "content": "[default]\naws_access_key_id = AKIAIOSFODNN7EXAMPLE\naws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\nregion = us-east-1"
            },
            {
                "filename": ".env.production",
                "path": "/root/",
                "content": "DATABASE_URL=postgresql://admin:Pr0d#Pass@db.internal:5432/prod\nREDIS_URL=redis://:R3dis!Pass@cache.internal:6379\nJWT_SECRET=super-secret-jwt-key-do-not-share"
            },
            {
                "filename": "docker-compose-prod.yml",
                "path": "/root/",
                "content": "version: '3'\nservices:\n  db:\n    image: postgres:14\n    environment:\n      POSTGRES_PASSWORD: Pr0dDB#2024\n  app:\n    environment:\n      SECRET_KEY: app-secret-2024"
            },
            {
                "filename": "k8s-secrets.yaml",
                "path": "/root/",
                "content": "apiVersion: v1\nkind: Secret\ndata:\n  db-password: UHIwZERCIzIwMjQ=\n  api-key: c2stcHJvZC1hYmMxMjM="
            },
        ],
        'general': [
            {
                "filename": "passwords.txt",
                "path": f"/home/{profile.get('users', ['user'])[0]}/",
                "content": "Email: MyP@ssw0rd!\nGmail: Gm@il2024#\nSSH: S3cur3SSH!\nAdmin: Adm1n#Pass"
            },
            {
                "filename": "credentials_backup.txt",
                "path": f"/home/{profile.get('users', ['user'])[0]}/Documents/",
                "content": "Server login: admin / Adm!n2024\nDatabase: dbuser / DB#Secure\nVPN: vpnuser / Vpn@Pass"
            },
            {
                "filename": "id_rsa_backup",
                "path": f"/home/{profile.get('users', ['user'])[0]}/",
                "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA2a2rwplBQLF29amygykEMmYz0+Kcj3bKBp29S2rFNwCHFW\n-----END RSA PRIVATE KEY-----"
            },
            {
                "filename": "network_config.txt",
                "path": "/root/",
                "content": "Router Admin: admin / R0ut3r#2024\nSwitch: cisco / Sw!tch2024\nFirewall: admin / F1r3wall#"
            },
        ]
    }

    return templates.get(system_type, templates['general'])

if __name__ == "__main__":
    from hivebee.scanner import scan
    import json
    profile = scan()
    files = generate_honeyfiles(profile)
    print(json.dumps(files, indent=2))
